Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python dpkt不生成tcp对象_Python - Fatal编程技术网

Python dpkt不生成tcp对象

Python dpkt不生成tcp对象,python,Python,尝试使用dpkt解析pcap。获取了以下示例代码,但出现了错误: Traceback (most recent call last): File "te.py", line 14, in <module> print tcp.sport AttributeError: 'str' object has no attribute 'sport' 这两条评论是正确的。从中读取的数据包没有像TCP或UDP这样的链路层。 因此,在读取数据包中的下一层之前,请检查它是否存在 这将

尝试使用dpkt解析pcap。获取了以下示例代码,但出现了错误:

Traceback (most recent call last):
  File "te.py", line 14, in <module>
    print tcp.sport
AttributeError: 'str' object has no attribute 'sport'

这两条评论是正确的。从中读取的数据包没有像TCP或UDP这样的链路层。 因此,在读取数据包中的下一层之前,请检查它是否存在

这将帮助您:

# Check for TCP or UDP packets
if ip.p == dpkt.ip.IP_PROTO_TCP or ip.p == dpkt.ip.IP_PROTO_UDP:
在您的示例中,它如下所示:

import dpkt
import sys

f = open("email1b.pcap")
pcap = dpkt.pcap.Reader(f)

for ts, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    ip = eth.data
     
     # Check if there is TCP in packet
     if ip.p == dpkt.ip.IP_PROTO_TCP:
        tcp = ip.data
        print tcp.sport

     else:
        print "there is no TCP in the packet"

f.close()

您确定只捕获了TCP数据包吗?感谢您提出的问题,使我们认识到前两个数据包是ARP,其余是TCP数据包。
import dpkt
import sys

f = open("email1b.pcap")
pcap = dpkt.pcap.Reader(f)

for ts, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    ip = eth.data
     
     # Check if there is TCP in packet
     if ip.p == dpkt.ip.IP_PROTO_TCP:
        tcp = ip.data
        print tcp.sport

     else:
        print "there is no TCP in the packet"

f.close()