首页 > 解决方案 > 使用python在pcap文件中获取数据包类型的第一个和最后一个时间戳

问题描述

我几乎是 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")

标签: pythontimestampanalysispacketpcap

解决方案


一种方法是为 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]

推荐阅读