跳转到主要内容
实验编号: 002

Raw Socket Packet Sniffer

活跃

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 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    fin = flags & 0x0120    return tcph[0], tcph[1], syn2122def 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 only30                continue31            sp, dp, syn = parse_tcp(raw, offset)32            if syn:33                print(f"[SYN] {src}:{sp} -> {dst}:{dp}")34        except struct.error:35            continue3637if __name__ == "__main__":38    sniff()
只读模式UTF-8