Con*_*CPP 9 python network-programming packet-capture pcap libpcap
我有一个python脚本使用dpkt捕获以太网上的数据包,但我如何区分哪些数据包是tcp和哪些数据包是udp.
最终,我希望在该时间间隔内建立每个tcp连接的数据包列表.
我的代码是:
import dpkt
import pcapy
cap=pcap.open_live('eth0',100000,1,0)
(header,payload)=cap.next()
while header:
eth=dpkt.ethernet.Ethernet(str(payload))
ip=eth.data
tcp=ip.data
# i need to know whether it is a tcp or a udp packet here!!!
(header,payload)=cap.next()
Run Code Online (Sandbox Code Playgroud)
IP头包含字段协议.dpkt应该允许你获得这个值并使用它你可以猜出IP之上是什么.以下是有效协议编号列表http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml.UDP等于17,而TCP为6.
编辑:我已经检查过这个问题,正如我所提到的,dpkg提供p了访问IP协议字段的属性.所以你可以再次检查它.但它也会自动将数据包和set data属性解析为代表UDP或TCP等上层协议的类实例.因此,您可以检查data属性的类型,并识别此协议.
from dpkt.ip import IP, IP_PROTO_UDP
from dpkt.udp import UDP
ip = IP('E\x00\x00"\x00\x00\x00\x00@\x11r\xc0\x01\x02\x03\x04\x01\x02\x03\x04\x00o\x00\xde\x00\x0e\xbf5foobar')
#if ip.p == IP_PROTO_UDP: # checking for protocol field in ip header
if type(ip.data) == UDP : # checking of type of data that was recognized by dpkg
udp = ip.data
print udp.sport
else:
print "Not UDP"
Run Code Online (Sandbox Code Playgroud)
小智 6
Python脚本捕捉以太网适配器上的包eth0使用dpkt,并区分TCP和UDP的数据包的IP.
import dpkt
import pcapy
cap=pcapy.open_live('eth0',100000,1,0)
(header,payload)=cap.next()
while header:
eth=dpkt.ethernet.Ethernet(str(payload))
# Check whether IP packets: to consider only IP packets
if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
continue
# Skip if it is not an IP packet
ip=eth.data
if ip.p==dpkt.ip.IP_PROTO_TCP: # Check for TCP packets
TCP=ip.data
# ADD TCP packets Analysis code here
elif ip.p==dpkt.ip.IP_PROTO_UDP: # Check for UDP packets
UDP=ip.data
# UDP packets Analysis code here
(header,payload)=cap.next()
Run Code Online (Sandbox Code Playgroud)