Hi there I am building a packet analysis tool. So far my code simply opens the pcap, parses it and closes the file. The code I have used has been adapted from the dpkt documentation. My pcap test files use different types of traffic (tcp, udp, igmp and http) and I need to be able to summarise each of these traffic flows, ideally being able to identify the traffic type adaptively as new ones appear. I need to include first and last timestamps for each type, a mean packet length and total number of packets. Sorry if it's a beginners question I'm just really struggling to use the dpkt documentation as I'm fairly new to python. At the moment I just have the output set to show the src and dst IP, packet length and timestamp. And help would be appreciated.
import dpkt
import datetime
import socket
import sys
import collections
def inet_string(inet):
try:
return socket.inet_ntop(socket.AF_INET, inet)
except ValueError:
return socket.inet_ntop(socket.AF_INET6, inet)
'''Function for printing the packet information'''
def print_packets(pcap):
for ts, buf in pcap:
# Print out the timestamp in UTC
print('Timestamp: ', str(datetime.datetime.utcfromtimestamp(ts)))
# Unpack the Ethernet frame
eth = dpkt.ethernet.Ethernet(buf)
# Make sure the Ethernet data contains an IP packet
if not isinstance(eth.data, dpkt.ip.IP):
print('Non IP Packet type not supported %s\n' % eth.data.__class__.__name__)
continue
# Unpack the IP packet
ip = eth.data
# Unpack TCP
tcp = ip.data
# Print out the info
print(f'{inet_string(ip.src)} -> {inet_string(ip.dst)} Packet Length: {ip.len}')
def main():
#Test Arguments
#sys.argv.append('packets1.pcap')
sys.argv.append('packets2.pcap')
with open(sys.argv[1], 'rb') as f:
pcap = dpkt.pcap.Reader(f)
print_packets(pcap)
if __name__ == '__main__':
main()