Experiment: 002
Raw Socket Packet Sniffer
ActivePython script using raw sockets to capture and parse TCP/IP headers manually. Prints TCP SYN packets as the starting point for scan detection, without relying on libpcap.
Objective
Manually parse IP/TCP headers to understand protocol structures and detect scanning patterns without relying on Wireshark.
Constraints
Requires root/admin privileges. Linux only (AF_PACKET). For macOS use BPF socket instead.
- Python
- Networking
- Raw Sockets
Source code · original languagesrc/main.py
1import socket2import struct34ETH_P_IP = 0x080056def parse_ip(raw: bytes) -> tuple[int, int, str, str]:7 # Skip 14-byte Ethernet header on AF_PACKET8 iph = struct.unpack("!BBHHHBBH4s4s", raw[14:34])9 ihl = (iph[0] & 0xF) * 410 proto = iph[6]11 src = socket.inet_ntoa(iph[8])12 dst = socket.inet_ntoa(iph[9])13 return ihl + 14, proto, src, dst1415def parse_tcp(raw: bytes, offset: int) -> tuple[int, int, int]:16 tcph = struct.unpack("!HHLLBBHHH", raw[offset:offset + 20])17 flags = tcph[5]18 syn = (flags & 0x02) >> 119 return tcph[0], tcph[1], syn2021def sniff() -> None:22 sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_IP))23 print("[*] Sniffing TCP — Ctrl+C to stop")24 while True:25 raw, _ = sock.recvfrom(65535)26 try:27 offset, proto, src, dst = parse_ip(raw)28 if proto != 6: # TCP only29 continue30 sp, dp, syn = parse_tcp(raw, offset)31 if syn:32 print(f"[SYN] {src}:{sp} -> {dst}:{dp}")33 except struct.error:34 continue3536if __name__ == "__main__":37 sniff()Read-only codeUTF-8