1. The Scapy Framework: Layer Stacking Paradigm
While Python's native socket library handles byte streams, crafting bespoke headers with custom flags, sequence numbers, and checksums requires painful manual bitmasking and binary packing via struct.pack().
Scapy fundamentally redefines packetcrafting by representing network protocols as first-class Python classes. Scapy overloads Python's division operator (/) into an elegant layer composition operator:
Custom Packet Encapsulation:
+-------------------------------------------------------------+
| Layer 2: Ether(dst="ff:ff:ff:ff:ff:ff", src="00:11:22:...") |
+-------------------------------------------------------------+
/
+-------------------------------------------------------------+
| Layer 3: IP(dst="192.168.1.1", ttl=64, id=1337) |
+-------------------------------------------------------------+
/
+-------------------------------------------------------------+
| Layer 4: TCP(sport=54321, dport=443, flags="S", seq=100) |
+-------------------------------------------------------------+
/
+-------------------------------------------------------------+
| Layer 7: Raw(load="GET / HTTP/1.1\r\nHost: target\r\n\r\n") |
+-------------------------------------------------------------+In Scapy, fields left unspecified are automatically computed with valid, RFC-compliant defaults (e.g., checksums, packet lengths, source IP addresses, and IP identification numbers are calculated at send time).
2. Layer 2 Discovery: The ARP Ping
When scanning an entire subnet (e.g., 192.168.1.0/24), sending ICMP Echo Requests (ping) is frequently defeated because modern endpoint firewalls (Windows Defender Firewall, macOS pf) silently discard unsolicited ICMP packets.
However, no operating system connected to an Ethernet broadcast domain can ignore Address Resolution Protocol (ARP) requests. To deliver any IP frame, the host must resolve the destination IP address into a 48-bit MAC hardware address:
#!/usr/bin/env python3
"""
High-Speed Layer-2 ARP Subnet Scanner using Scapy
"""
import sys
from scapy.all import Ether, ARP, srp
def arp_scan(subnet: str) -> list:
"""Broadcasts ARP requests across a subnet and returns live hosts."""
print(f"[*] Dispatching ARP broadcast requests across: {subnet}")
# Construct Ethernet Broadcast Frame enclosing ARP Request
broadcast_frame = Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=subnet)
# srp() sends and receives packets at Layer 2 (data link layer)
answered, unanswered = srp(broadcast_frame, timeout=2.5, verbose=False)
live_hosts = []
for sent, received in answered:
live_hosts.append({
"ip": received.psrc,
"mac": received.hwsrc
})
return live_hosts
if __name__ == "__main__":
target_net = sys.argv[1] if len(sys.argv) > 1 else "192.168.1.0/24"
results = arp_scan(target_net)
print(f"\n{'IP Address':<18} {'Hardware MAC Address':<20}")
print("-" * 38)
for host in results:
print(f"{host['ip']:<18} {host['mac']:<20}")3. Layer 4 Custom Traceroute Implementation
Traceroute diagnostics determine the exact router path packets traverse to reach a remote destination. It exploits the Time-To-Live (TTL) field in the IPv4 header.
Each intermediate Layer 3 router that forwards an IP packet decrements its TTL by 1. When a router receives a packet with TTL = 1, it cannot decrement further; it drops the packet and transmits an ICMP Type 11 (Time Exceeded) message back to the originating IP address:
#!/usr/bin/env python3
"""
Custom Python Traceroute using Scapy and TTL Dilation
"""
import sys
from scapy.all import IP, TCP, sr1
def custom_traceroute(destination: str, max_hops: int = 30) -> None:
print(f"[*] Tracing route to {destination} over max {max_hops} hops:\n")
for ttl in range(1, max_hops + 1):
# Craft IP packet with incrementally dilated TTL targeting TCP port 80
pkt = IP(dst=destination, ttl=ttl) / TCP(dport=80, flags="S")
# sr1() sends Layer 3 packet and waits for single response
reply = sr1(pkt, timeout=1.5, verbose=False)
if reply is None:
print(f"{ttl:<3} * * * (Request Timed Out)")
elif reply.haslayer(TCP):
# Target reached! Host responded with TCP SYN/ACK or RST
print(f"{ttl:<3} {reply.src:<18} [Target Port Reached]")
break
elif reply.haslayer(ICMP):
icmp_layer = reply.getlayer(ICMP)
# ICMP Type 11 indicates Time Exceeded in transit
if icmp_layer.type == 11:
print(f"{ttl:<3} {reply.src:<18} [ICMP Time Exceeded]")
else:
print(f"{ttl:<3} {reply.src:<18} [ICMP Type {icmp_layer.type}]")
if __name__ == "__main__":
target = sys.argv[1] if len(sys.argv) > 1 else "8.8.8.8"
custom_traceroute(target)