我正在尝试获取流的最小、最大数据包大小,以及来自我捕获的网络流量的数据包之间的到达时间。我已经尝试过,但我没有取得任何进展。
下面的代码: 1. 统计pcap文件中TCP流的数量。
2. 统计 pcap 文件中 UDP 流的数量。
3. 统计唯一 IP 地址的数量。
4. 计算每个流的数据包总数。
5. 计算每个流的平均数据包大小。
6. 计算每个流程的持续时间。请我非常感谢你的帮助!!
这是下面的代码
import dpkt
from functools import reduce
import socket
import statistics
tflows = {}
uflows = {}
ips = set()
#Counters
counter=0
ipcounter=0
nonipcounter=0
pktcounter=0
ipv4counter=0
totaltcpcounter=0
totaludpcounter=0
def dumpFlow(flows, flow):
print(f'Data for flow: {flow}:')
bytes = reduce(lambda x, y: x+y,
map(lambda e: e['byte_count'], flows[flow]))
packets = reduce(lambda a, z: a+z,
map(lambda e: e['packet_count'], flows[flow]))
Flow_protocol = sorted(map(lambda e: e['protocol'], flows[flow]))
Flow_protocol = (Flow_protocol[0])
duration = sorted(map(lambda e: e['ts'], flows[flow]))
duration = duration[-1] - duration[0]
print(f"\tTotal Bytes: {bytes}")
print(f"\tTotal Number of Packets per flow: {packets}")
print(f"\tAverage Bytes: {bytes / len(flows[flow])}")
print(f"\tTotal Duration: {duration}")
print(f"\tMean Packets: {packets / 2}")
print(f"\tFlow Protocol: {Flow_protocol}")
# Packet processing loop
for ts,pkt in dpkt.pcap.Reader(open('tesst.pcap','rb')):
pktcounter = 0
counter+=1
eth=dpkt.ethernet.Ethernet(pkt)
#check if IP packet or non-ip packet
if eth.type == dpkt.ethernet.ETH_TYPE_IP:
ipcounter = ipcounter + 1
else:
nonipcounter = nonipcounter + 1
if eth.type==dpkt.ethernet.ETH_TYPE_IP:
ipv4counter+=1
ip=eth.data
# determine transport layer type
if ip.p==dpkt.ip.IP_PROTO_TCP:
pktcounter+=1
totaltcpcounter+=1
flows = tflows
elif ip.p==dpkt.ip.IP_PROTO_UDP:
pktcounter+=1
totaludpcounter+=1
flows = uflows
# extract IP and transport layer data
src_ip = socket.inet_ntoa(ip.src)
src_port = ip.data.sport
dst_ip = socket.inet_ntoa(ip.dst)
dst_port = ip.data.dport
# keeping set of unique IPs
ips.add(src_ip)
ips.add(dst_ip)
# store flow data
flow = sorted([(src_ip, src_port), (dst_ip, dst_port)])
#print(flow)
flow = (flow[0], flow[1])
flow_data = {
'byte_count': len(eth),
'packet_count': (pktcounter),
'ts': ts,
'protocol': ip.p
}
if flows.get(flow):
flows[flow].append(flow_data)
else:
flows[flow] = [flow_data]
print ("Total number of ETHERNET packets in the PCAP file :", counter)
print ("\t\tTotal number of IP packets :", ipcounter)
print ("\t\tTotal number of TCP packets :", totaltcpcounter)
print ("\t\tTotal number of UDP packets :", totaludpcounter)
print ("\t\tTotal number of IPV4 packets :", ipv4counter)
print ("\t\tTotal number of NON-IP packets :", nonipcounter)
print ("----------------------------------------------------------------------")
print(f'Total number of TCP flows: {len(tflows.keys())}')
print(f'Total number of UDP flows: {len(uflows.keys())}')
print(f'Total number of unique IPs: {len(ips)}')
for k in tflows.keys():
dumpFlow(tflows, k)
for k in uflows.keys():
dumpFlow(uflows, k)