Skip to main content
实验编号: 002

Raw Socket Packet Sniffer

ACTIVE

Python script utilizing raw sockets to capture and parse TCP/IP headers manually. Implements basic SYN-scan detection without relying on libpcap.

目标

Manually parse IP/TCP headers to understand protocol structures and detect scanning patterns without relying on Wireshark.

约束

Requires root/admin privileges. Linux only (AF_PACKET). For macOS use BPF socket instead.

Python Networking Raw Sockets
src/main.py
1import socket
2import struct
3
4ETH_P_IP = 0x0800
5
6def parse_ip(raw: bytes) -> tuple[int, int, str, str]:
7 # Skip 14-byte Ethernet header on AF_PACKET
8 iph = struct.unpack("!BBHHHBBH4s4s", raw[14:34])
9 ihl = (iph[0] & 0xF) * 4
10 proto = iph[6]
11 src = socket.inet_ntoa(iph[8])
12 dst = socket.inet_ntoa(iph[9])
13 return ihl + 14, proto, src, dst
14
15def 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) >> 1
19 fin = flags & 0x01
20 return tcph[0], tcph[1], syn
21
22def sniff() -> None:
23 sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_IP))
24 print("[*] Sniffing TCP — Ctrl+C to stop")
25 while True:
26 raw, _ = sock.recvfrom(65535)
27 try:
28 offset, proto, src, dst = parse_ip(raw)
29 if proto != 6: # TCP only
30 continue
31 sp, dp, syn = parse_tcp(raw, offset)
32 if syn:
33 print(f"[SYN] {src}:{sp} -> {dst}:{dp}")
34 except struct.error:
35 continue
36
37if __name__ == "__main__":
38 sniff()
只读模式UTF-8