Python 中的数据包嗅探器

E. *_*ams 2 python sockets networking sniffer

我想用 Python 3.5 做一个数据包嗅探器,捕获 UDP、TCP 和 ICMP。这是一个简短的例子:

 import socket
 import struct

# the public network interface
HOST = socket.gethostbyname(socket.gethostname())
# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)

s.bind((HOST,0))

# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

# receive a package
n=1
while(n<=400):
    print('Number ', n)
    data=s.recvfrom(65565)
    packet=data[0]
    address= data[1]
    header=struct.unpack('!BBHHHBBHBBBBBBBB', packet[:20])
    if(header[6]==6): #header[6] is the field of the Protocol
        print("Protocol = TCP")
    elif(header[6]==17):
        print("Protocol = UDP")
    elif(header[5]==1):
        print("Protocol = ICMP") 
    n=n+1
Run Code Online (Sandbox Code Playgroud)

问题是它只捕获 UDP 数据包:( 输出:

Number  1 Protocol = UDP Number  2 Protocol = UDP Number  3 Protocol = UDP Number  4 Protocol = UDP Number  5 Protocol = UDP Number  6 Protocol = UDP Number  7
Run Code Online (Sandbox Code Playgroud)

有 2 个选项:

  • 嗅探器只能捕获UDP数据包。
  • 我刚刚收到 UDP 数据包。

我认为最合乎逻辑的答案是我的嗅探器无法正常工作,它只是捕获 UDP。任何想法?

小智 6

我自己正处于创建 python 数据包解析器/嗅探器的阶段,在我的研究中我发现,为了能够解析所有传入数据包,如 TCP、ICMP、UDP、ARP 等,您不能使用以下套接字type 因为socket.IPPROTO_IP只给出 IP 数据包并且是一个虚拟协议

s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
Run Code Online (Sandbox Code Playgroud)

相反,你必须使用它并且在 Linux 系统上工作得最好

s = socket.socket( socket.AF_PACKET , socket.SOCK_RAW , socket.ntohs(0x0003))
Run Code Online (Sandbox Code Playgroud)