EXPERIMENT_ID: 002

Raw Socket Packet Sniffer

ACTIVE

Python script utilizing raw sockets to capture and analyze TCP/IP headers. Implements basic signature matching for identifying SYN scans.

OBJECTIVE

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

CONSTRAINTS

Requires root/admin privileges. Promiscuous mode enabled.

Python Networking Scapy
src/main.python
1
2import socket
3import struct
4
5def sniff():
6 # Create a raw socket bound to all interfaces
7 # AF_PACKET is Linux specific. For Windows use AF_INET + IP_HDRINCL
8 s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
9
10 while True:
11 raw_data, addr = s.recvfrom(65535)
12 eth_header = raw_data[:14]
13
14 # Unpack Ethernet Frame
15 dest, src, proto = struct.unpack('! 6s 6s H', eth_header)
16
17 # Check for IPv4 (0x0800)
18 if socket.ntohs(proto) == 8:
19 ip_header = raw_data[14:34]
20 # Unpack IP Header (Version, IHL, TTL, Protocol, Source, Dest)
21 iph = struct.unpack('!BBHHHBBH4s4s', ip_header)
22
23 version_ihl = iph[0]
24 ihl = version_ihl & 0xF
25
26 print(f"Packet: {addr} | IHL: {ihl} | Protocol: {iph[6]}")
27
READ_ONLY_MODEUTF-8