A beginner-friendly TCP/IP packet sniffer written in Python, demonstrating how to capture and parse basic network packet information using only the standard library.
- Raw socket packet capture: Listens to all incoming and outgoing packets, using Python's
socketandstructmodules. - IP header parsing: Extracts and displays key fields such as IP version, header length, TTL, protocol, source, and destination addresses.
- Protocol identification: Recognizes common protocols (ICMP, TCP, UDP) and displays their names.
- DNS packet highlighting: Detects DNS queries/responses by checking for UDP packets on port 53, and prints details for those packets.
- Promiscuous mode support: Enables capturing all packets on the network interface (Windows only).
-
Raw Socket Creation:
The program creates a raw IP socket usingsocket.AF_INETandsocket.SOCK_RAW, binding it to the host's network interface. -
Promiscuous Mode (Windows):
By settingsocket.SIO_RCVALL, the sniffer receives all packets traversing the interface. -
Packet Capture Loop:
In an infinite loop, it callsrecvfrom()to receive packets, then parses:- The first 20 bytes as the IP header (
struct.unpack). - Extracts protocol, TTL, source/destination IPs, and header length.
- Identifies the protocol using a lookup dictionary.
- The first 20 bytes as the IP header (
-
UDP/DNS Detection:
If the packet is UDP, it further unpacks the UDP header and checks if either source or destination port is 53 (DNS). If so, it prints additional info. -
Graceful Shutdown:
OnCtrl+C, the sniffer disables promiscuous mode and closes the socket.
Simple Packet Sniffer - Press Ctrl+C to stop
Packet #1: Version=4, HeaderLen=20, TTL=128, Protocol=TCP, Src=192.168.1.5, Dst=8.8.8.8
Packet #2: Version=4, HeaderLen=20, TTL=128, Protocol=UDP, Src=192.168.1.5, Dst=8.8.8.8
DNS Query: SrcPort=55321, DstPort=53
...
- Python 3
- Administrator/root privileges are required to run raw sockets.
- Windows only: Promiscuous mode is enabled using
ioctl. On Linux, root is required andpromiscuousmode may be enabled differently.
This implementation uses only Python's standard library to demonstrate how raw sockets and protocol parsing work at a low level, making it more educational for beginners.
- Only parses IPv4 packets.
- DNS detection is basic and not a full protocol parser.
- Promiscuous mode is implemented for Windows; adaptation is needed for Linux/macOS.
- Run the script as administrator/root:
python packet_peek.py
- Watch the output for live packet info!
- Stop with
Ctrl+C.
This project is intended for learning about networking and packet analysis in Python. For advanced packet sniffing and protocol parsing, consider tools like Scapy or Wireshark.
MIT License