Signup/Sign In

Analyzing Networking Traffic using dpkt library

We will be using the dpkt library to analyse the network traffic. dpkt is a python module for fast, simple packet creation/parsing, with definition for the basic TCP/IP protocols. In order to use dpkt you first need to install it.


Intalling dpkt module

sudo pip install dpkt

Note: You can omit sudo from the above command, if you are logged in as root user.

In this lesson we will extract the source IP and destination IP addressess for the packets on the network using python code, from our .pcap file, in which we saved the Workshire traffic data. After saving your captured pcap file at some location(say Desktop). Run the following code:

#!usr/bin/env python
# this code prints Source and Destination IP from the given 'pcap' file

import dpkt
import socket

def printPcap(pcap):
	for (ts,buf) in pcap:
		try:
			eth = dpkt.ethernet.Ethernet(buf)
			ip = eth.data
			# read the source IP in src
			src = socket.inet_ntoa(ip.src)
			# read the destination IP in dst
			dst = socket.inet_ntoa(ip.dst)

			# Print the source and destination IP
			print 'Source: ' +src+ ' Destination: '  +dst

		except:
			pass

def main():
	# Open pcap file for reading
	f = open('/home/codeplay/Desktop/first.pcap')
	#pass the file argument to the pcap.Reader function
	pcap = dpkt.pcap.Reader(f)
	printPcap(pcap)

if __name__ == '__main__':
	main()

In the above code, in the method printPcap(), ts and buf are timestamp and buffer respectively. You might have noticed socket methods inet_ntoa and inet_aton. inet_aton converts a 32-bit packed IPv4 address(a string of four characters in length) to its standard dotted-quad string representation(for example, 123.45.67.89).

Output:

Analyzing Network Traffic uing dpkt library