Simple Raw Packet Sniffer In Python

user3490561 picture user3490561 · Jul 10, 2014 · Viewed 19.5k times · Source

First, I'm a beginner in python. I developed a simple raw packet sniffer utilizing the PF_PACKET interface that operates at layer 2.

The sniffer simply figures out the following... - Ethernet Header (Source - Destination - Protocol) - IP Header (Source IP - Destination IP) - TCP Header(Source Port - Destination Port)

Here's the code I've written so far...

#!/usr/bin/env python
import struct
import socket
import binascii

rawSocket=socket.socket(socket.PF_PACKET,socket.SOCK_RAW,socket.htons(0x0800))
#ifconfig eth0 promisc up
receivedPacket=rawSocket.recv(2048)

#Ethernet Header...
ethernetHeader=receivedPacket[0][0:14]
ethrheader=struct.unpack("!6s6s2s",ethernetHeader)
destinationIP= binascii.hexlify(ethrheader[0])
sourceIP= binascii.hexlify(ethrheader[1])
protocol= binascii.hexlify(ethrheader[2])
print "Destinatiom: " + destinationIP
print "Souce: " + sourceIP
print "Protocol: "+ protocol

#IP Header... 
ipHeader=receivedPacket[0][14:34]
ipHdr=struct.unpack("!12s4s4s",ipHeader)
destinationIP=socket.inet_ntoa(ipHdr[2])
print "Source IP: " +sourceIP
print "Destination IP: "+destinationIP

#TCP Header...
tcpHeader=receivedPacket[0][34:54]
tcpHdr=struct.unpack("!2s2s16s",tcpHeader)
sourcePort=socket.inet_ntoa(tcpHdr[0])
destinationPort=socket.inet_ntoa(tcpHdr[1])
print "Source Port: " + sourcePort
print "Destination Port: " + destinationPort

I seem to encounter a problem in the ethernet header part and the unpack method that I can't figure out. Thanks in advance :)

Answer

Peter Gibson picture Peter Gibson · Jul 10, 2014

You have an extra [0] in your string slicing statement:

ethernetHeader=receivedPacket[0][0:14]

Should be just

ethernetHeader=receivedPacket[0:14]

The error is telling you that struct.unpack requires a string of length 14. If you print the string you're passing to it, you'll probably see that it only has length = 1. Here's an example:

>>> s = 'this is a test'
>>> s[0]
't'
>>> s[0][0:4]
't'
>>> s[0:4]
'this'