实验编号: 002
原始套接字抓包工具
活跃通过原始套接字捕获并手动解析 TCP/IP 首部的 Python 脚本;打印 TCP SYN 数据包作为扫描检测的起点,不依赖 libpcap。
目标
手动解析 IP/TCP 首部,以理解协议结构并在不依赖 Wireshark 的情况下检测扫描模式。
约束
需要 root 或管理员权限。仅适用于 Linux 的 AF_PACKET;macOS 应使用 BPF 套接字。
- Python
- 网络
- 原始套接字
源代码 · 原始语言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 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()只读代码UTF-8