3

我正在用 python 编程,但我遇到了一个问题,事实上,当我抛出我的脚本时,它在他检测到 IP6 数据包后几秒钟就结束了。显然我必须过滤数据包并只接收 IP4 数据包以避免这个问题,我想知道我如何在开始时将它与库 dpkt 一起使用。我尝试了一些东西,但我是一个初学者,它不起作用,正如你在这一行中看到的那样:

#Select Ipv4 packets because of problem with the .p in Ipv6
            if ip.p == dpkt.ip6:
                return`

遇到的错误说:“AttributeError:'IP6'对象没有属性'p'”。这是回溯: 追溯

这是我的代码,如果你想看看 :) 谢谢你的时间 :)

import pcapy
import dpkt
from threading import Thread
import re
import binascii

liste=[]
listip=[]
piece_request_handshake = re.compile('13426974546f7272656e742070726f746f636f6c(?P<reserved>\w{8})(?P<info_hash>\w{20})(?P<peer_id>\w{20})')
piece_request_tcpclose = re.compile('(?P<start>\w{12})5011')


class PieceRequestSniffer(Thread):
    def __init__(self, dev='eth0'):
        Thread.__init__(self)

        self.expr = 'udp or tcp'

        self.maxlen = 65535  # max size of packet to capture
        self.promiscuous = 1  # promiscuous mode?
        self.read_timeout = 100  # in milliseconds
        self.max_pkts = -1  # number of packets to capture; -1 => no limit

        self.active = True
        self.p = pcapy.open_live(dev, self.maxlen, self.promiscuous, self.read_timeout)
        self.p.setfilter(self.expr)

    @staticmethod
    def cb(hdr, data):

        eth = dpkt.ethernet.Ethernet(str(data))
        ip = eth.data

        #Select only TCP protocols
        if ip.p == dpkt.ip.IP_PROTO_TCP:
            tcp = ip.data

            #Select Ipv4 packets because of problem with the .p in Ipv6
            if ip.p == dpkt.ip6:
                return
            else:
                try:
                    #Return hexadecimal representation
                    hex_data = binascii.hexlify(tcp.data)
                except:
                    return                

                handshake = piece_request_handshake.findall(hex_data)
                if handshake:
                    print "-----------handsheck filtered-------------"
                    liste.append(handshake)
                    print "\n"
                    #for element in zip(liste,"123456789abcdefghijklmnopqrstuvwxyz"):
                    #    print(element)



    def stop(self):
        self.active = False

    def run(self):
        while self.active:
            self.p.dispatch(0, PieceRequestSniffer.cb)


sniffer = PieceRequestSniffer()
sniffer.start()
4

1 回答 1

2

最后我找到了这样做的好方法,这条线不是:

if ip.p == dpkt.ip6:
                return

但:

if eth.type == dpkt.ethernet.ETH_TYPE_IP6:
                    return
于 2015-04-28T10:20:16.107 回答