【发布时间】:2016-06-04 20:02:03
【问题描述】:
我想在 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
问题是它只捕获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
有两种选择:
- 嗅探器只能捕获 UDP 数据包。
- 我只是在接收 UDP 数据包。
我认为最合乎逻辑的答案是我的嗅探器无法正常工作,它只是在捕获 UDP。有什么想法吗?
【问题讨论】:
-
我敢打赌 Scapy 比 socket 模块更适合这项工作。嗅探数据包要舒服得多。
-
您使用的是什么平台?在 Unix/Linux 上,您通常需要 root 才能捕获每个数据包。
-
@HughFisher 我在 Windows 7 上,使用 PyDev 和 Eclipse。我正在以管理员身份执行 eclipse。
标签: python sockets networking sniffer