python - 使用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")
解决方案
一种方法是为 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]
推荐阅读
- powershell - 从 powershell 向 cmd 传递命令
- selenium-webdriver - 未使用 xpath 选中复选框,它会打开链接
- rest - Magento 1.* rest API php oauth 身份验证
- python - Unicode 编码错误 'latin-1' 编解码器无法在位置 4939 对字符 u'\u2013' 进行编码:序数不在范围内(256)
- reactjs - 如何在 TypeScript 中获取 GraphQL 架构
- php - 如果密码验证条件中的条件在 php 中无法正常工作
- php - MySQL 上的 SELECT 不适用于我的 PHP 脚本,但适用于 phpmyadmin
- xamarin - Xamarin Java 库绑定问题
- excel - Excel VBA 编辑注释(如果存在)
- javascript - 结合单选按钮和文本字段