使用python获取pcap文件中数据包类型的第一个和最后一个时间戳

2024-09-27 00:18:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,我有一个小脚本来打印3种不同协议(tcp、udp和igmp)的数据包数量。我希望能够打印每种协议类型的第一个和最后一个时间戳,正如您从下面的代码中看到的,我目前有占位符时间戳,但这是临时的,有人知道我如何获得3种协议类型的第一个和最后一个时间戳吗

counter=0
ipcounter=0
tcpcounter=0
udpcounter=0
igmpcounter=0


filename = 'basic-packet-file.pcap'

for ts, pkt in dpkt.pcap.Reader(open(filename,'rb')):


    counter+=1
    eth=dpkt.ethernet.Ethernet(pkt)
    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
       continue

 

    ip=eth.data
    ipcounter+=1

 

    if ip.p==dpkt.ip.IP_PROTO_TCP: 
       tcpcounter+=1
 

    if ip.p==dpkt.ip.IP_PROTO_UDP:
       udpcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_IGMP:
       igmpcounter+=1
       


print ("\t Total number of packets in the pcap file: ", ipcounter)
print ("\t Protocol type: \t Number of packets: \t Mean packet length \t First timestamp \t Last timestamp ")
print ("\t TCP: \t\t\t", tcpcounter, "\t\t\t Testmean", "\t\t 00:00", "\t\t\t 00:00")
print ("\t UDP: \t\t\t", udpcounter, "\t\t\t Testmean", "\t\t 00:00", "\t\t\t 00:00")
print ("\t IGMP: \t\t\t", igmpcounter, "\t\t\t Testmean", "\t\t 00:00", "\t\t\t 00:00")

Tags: ip协议if时间pcapprotoethprint
1条回答
网友
1楼 · 发布于 2024-09-27 00:18:23

一种方法是为TCP、UDP和IGMP中的每一个创建3个时间戳列表1,然后可以按时间戳对每个列表进行排序,并通过计算每个列表的长度获得每种数据包的总数

下面的示例显示了仅对TCP数据包需要执行的操作,但UDP和IGMP的逻辑相同

TCP_timestamps = []
packets = []

for ts, pkt in dpkt.pcap.Reader(open(filename,'rb')):
    eth = dpkt.ethernet.Ethernet(pkt)
    if eth.type != dpkt.ethernet.ETH_TYPE_IP:
        continue
    
    packet = eth.data
    packets.append(packet)

    if packet.p == dpkt.ip.IP_PROTO_TCP: 
        TCP_timestamps.append(ts)

TCP_timestamps.sort()


number_of_tcp_packtes = len(TCP_timestamps)
earliest_TCP = TCP_timestamps[0]
latest_TCP = TCP.timestamps[-1]

相关问题 更多 >

    热门问题