Packet sniffing in Python (Windows)

The hard way

You can sniff all of the IP packets using a raw socket.
Raw socket is a socket the sends and receives data in binary.
Binary in python is represented in a string which looks like this \x00\xff… every \x.. is a byte.
To read an IP packet you need to analyze the received packet in binary according to the IP protocol.

This is and image of the format of the IP protocol with the sized in bits of every header.

IP protocol format

This tutorial might help you understand the proccess of understanding a raw packet and splitting it to headers: http://www.binarytides.com/python-packet-sniffer-code-linux/

The easy way

Another method to sniff IP packets very easily is to use the scapy module.

from scapy.all import *
sniff(filter="ip", prn=lambda x:x.sprintf("{IP:%IP.src% -> %IP.dst%\n}"))

This code will print for you the source IP and the destination IP for every IP packet.
You can do much more with scapy by reading it’s documentation here: http://www.secdev.org/projects/scapy/doc/usage.html

It depends on the goal you are trying to achieve but if you need to build a project the one it’s features is sniffing IP packets then I recommend to use scapy for more stable scripts.

Leave a Comment