【发布时间】:2020-03-22 22:01:35
【问题描述】:
请我尝试使用 dpkt 在 python 中分析 pcap 文件。我想得到 1)唯一IP地址的数量, 2) 计算每个流的总字节数, 3) 每个流的数据包总数和 4) 每个流的平均数据包大小
如果有人可以帮助我解决上述问题的 python 代码,我将不胜感激。 谢谢
这就是我目前所做的
if __name__ == "__main__":
# Packet Counters
counter=0
ipcounter=0
nonipcounter=0
tcpcounter=0
udpcounter=0
httpcounter=0
httpscounter=0
ipv4counter=0
ipv6counter=0
# Subnet Dictionary
subnets = {}
# Open file
# Packet processing loop
for ts,pkt in dpkt.pcap.Reader(open('tesst.pcap','rb')):
counter+=1
# Parse ethernet packet
eth=dpkt.ethernet.Ethernet(pkt)
ip=eth.data
#check if IP packet or non-ip packet
if eth.type == dpkt.ethernet.ETH_TYPE_IP or eth.type == dpkt.ethernet.ETH_TYPE_IP6:
ipcounter = ipcounter + 1
else:
nonipcounter = nonipcounter + 1
# IPV6 packets
if eth.type==dpkt.ethernet.ETH_TYPE_IP6:
ipv6counter+=1
# IPV4 packets
elif eth.type==dpkt.ethernet.ETH_TYPE_IP:
ipv4counter+=1
# Extract destination
string = socket.inet_ntoa(ip.dst)
address = '.'.join(string.split(".")[:])
if address in subnets: #increase count in dict
subnets[address] = subnets[address] + 1
else: #insert key, value in dict
subnets[address] = 1
# TCP packets
if ip.p==dpkt.ip.IP_PROTO_TCP: #ip.p == 6:
tcpcounter+=1
tcp=ip.data
# HTTP uses port 80
if tcp.dport == 80 or tcp.sport == 80:
httpcounter+=1
# HTTPS uses port 443
elif tcp.dport == 443 or tcp.sport == 443:
httpscounter+=1
# UDP packets
elif ip.p==dpkt.ip.IP_PROTO_UDP: #ip.p==17:
udpcounter+=1
udp=ip.data
# Print packet totals
print ("Total number of ETHERNET packets in the PCAP file :", counter)
print ("\tTotal number of IP packets :", ipcounter)
print ("\t\tTotal number of TCP packets :", tcpcounter)
print ("\t\t\tTotal number of HTTP packets :", httpcounter)
print ("\t\t\tTotal number of HTTPS packets :", httpscounter)
print ("\t\t\tTotal number of IPV6 packets :", ipv6counter)
print ("\t\tTotal number of UDP packets :", udpcounter)
print ("\t\tTotal number of IPV4 packets :", ipv4counter)
print ("\tTotal number of NON-IP packets :", nonipcounter)
print ("--------------------------------------------------------------")
other = counter-(arpcounter+httpcounter+httpscounter+ipv6counter)
# Print addresses
print ("Address \t \t Occurences")
for key, value in sorted(subnets.items(), key=lambda t: int(t[0].split(".")[0])):
print ("%s/16 \t = \t %s" %(key, value))
【问题讨论】:
-
到目前为止你尝试过什么?你在哪里看过?
-
到目前为止你尝试过什么?请发布您的代码和可能的数据示例。
-
我能够输出IP包、TCP包、UDP包、IPV4和IPV6包的总数
-
@EricMPastore 我已经发布了我到目前为止所做的代码
-
@wobr 代码运行良好。我的代码可以输出 1)唯一 IP 地址的数量,2)计算每个流的字节总数,3)每个流的数据包总数和 4)每个流的平均数据包大小。我将立即发布输出