Lion Cipher Lab
Write a packet sniffer from scratch (raw AF_PACKET socket, parse Ethernet/IP/TCP by hand)
- Foundations
- Advanced
- ~75 min
- Free · no account required
Why it matters
Every packet-analysis tool you will ever touch -- Wireshark, tcpdump, Zeek, an IDS, your cloud provider's flow logs -- is, underneath the pretty columns, doing exactly what you are about to do by hand: pull raw bytes off an interface and decode fixed-offset headers into meaning. Most learners only ever meet those bytes as a coloured row in a GUI, which means when something is weird -- a malformed header, a tunnelled protocol, a field the tool does not decode -- they are stuck, because they have never seen the layout underneath the label. Writing a sniffer from scratch fixes that permanently.…
What you'll learn
- what a raw socket is, and why link-layer (Layer 2) capture is a privileged operation gated behind root / CAP_NET_RAW
- opening a raw packet socket in Python: socket.socket(AF_PACKET, SOCK_RAW, htons(0x0003)) and what ETH_P_ALL / htons actually mean
- parsing an Ethernet frame by hand with struct.unpack and byte slicing: destination MAC, source MAC, and the EtherType that names the next layer
- parsing an IPv4 header by hand: the packed version+IHL nibble, why header length is IHL*4 (32-bit words) and options make it exceed 20 bytes, total length, protocol number, and source/dest IP via inet_ntoa
- parsing TCP and UDP source/dest ports from the transport header and printing a tcpdump-style one-line summary per packet
- network byte order: why every multi-byte field is big-endian and you must unpack with '!' / ntohs or you get garbage
- the named failure modes that separate a toy from a tool: root requirement, byte order, the IHL*4 gotcha, 802.1Q VLAN offset shift, own-interface-only capture, and promiscuous mode
- the judgment of WHEN to write a raw sniffer vs use scapy/tcpdump/Wireshark, and HOW production capture pushes a BPF filter into the kernel and uses TPACKET_V3 mmap rings so junk packets never reach userspace
Steps in this lab
- What a raw socket is, and why capture needs root
- Open the raw AF_PACKET socket (build the sniffer, part 1)
- Parse the Ethernet frame by hand (part 2)
- Parse the IPv4 header, then TCP/UDP ports (part 3)
- Run it and make traffic to watch it work
- The named failure modes that separate a toy from a tool
- The judgment: when to write raw, and how the pros do it