Python Network Programming: Forging and Sniffing Packets with Scapy
Scapy helps learners understand how packet protocols are represented as layers and fields. For introductory study, the safest and most reproducible approach is to inspect locally generated or explicitly authorized captured packets rather than scan networks or transmit crafted traffic. A layered packet is data to reason about; observing it should not require probing public addresses.
A synthetic Ethernet/IPv4/UDP frame contains headers with distinct jobs: Ethernet identifies link-layer endpoints, IPv4 carries network-layer source/destination fields, and UDP carries ports and datagram length semantics. A transport port is not a host identity, and an IP address is not a MAC address. The layers can be composed in a local Python object without transmitting anything.
For live traffic, the only permissible scope is a network you own or are explicitly authorized to monitor. Packet capture can contain cookies, endpoint names, credentials or personal information even without any injection of traffic.
This example builds a Scapy packet object and summarizes its layers. This first example uses no network-interface capture, send, probe or scan operation. The packet uses reserved documentation address ranges rather than real target addresses.
from scapy.all import Ether, IP, UDP, Raw
packet = (
Ether(src="02:00:00:00:00:01", dst="02:00:00:00:00:02") /
IP(src="192.0.2.10", dst="192.0.2.20") /
UDP(sport=53000, dport=9000) /
Raw(load=b"test-only")
)
assert packet.haslayer(IP)
assert packet.haslayer(UDP)
print(packet.summary())
print("src", packet[IP].src, "dst", packet[IP].dst)
print("udp ports", packet[UDP].sport, packet[UDP].dport)
The addresses come from documentation-use space; no actual packets are transmitted. The exercise demonstrates field lookup and encapsulation. It is not a proof of reachability, packet delivery or any service availability.
If a separate approved exercise supplies a small sanitized PCAP file, a reader can parse the offline file rather than sniff a live interface. Record capture provenance and the limitations of the sample. Review whether timestamps, checksums and expected VLAN tags were preserved during sanitization. A single capture point does not show the complete route through a network.
A capture file can be huge or malformed. Limit file size and handle parser errors; do not assume arbitrary captured traffic is trustworthy.
To inspect a captured file without monitoring a live network, make one synthetic packet and write it to a local PCAP file. Scapy’s sniff(offline=...) API reads that file rather than a network interface. This example is self-contained, uses documentation-only IP addresses, caps its read at one packet and removes the temporary file after the demonstration.
from pathlib import Path
from scapy.all import Ether, IP, UDP, Raw, wrpcap, sniff
out = Path("synthetic-packet-example.pcap")
packet = (
Ether(src="02:00:00:00:00:01", dst="02:00:00:00:00:02") /
IP(src="192.0.2.10", dst="192.0.2.20") /
UDP(sport=53000, dport=9000) /
Raw(load=b"synthetic-test")
)
try:
# Save exactly one invented packet; do not transmit anything.
wrpcap(str(out), [packet])
# 'offline' reads a PCAP file; it does not monitor a live interface.
frames = sniff(offline=str(out), count=1, store=True)
assert len(frames) == 1
assert frames[0].haslayer(IP) and frames[0].haslayer(UDP)
print(frames[0].summary())
print(frames[0][IP].src, frames[0][IP].dst)
finally:
out.unlink(missing_ok=True)
The resulting trace proves only that Scapy serialized and parsed a fabricated protocol stack. It does not demonstrate a live packet being delivered, a host being reachable, or a secure network. For real, authorized troubleshooting, use approved and sanitized PCAP evidence with explicit capture scope and privacy controls. Scapy documents both wrpcap and offline sniffing in its packet import/export guide.
An ICMP Echo Reply can show that a host responded to that probe, while a TCP connection requires additional handshake state. A UDP datagram has no equivalent connection handshake, and the absence of a response does not establish packet loss or a closed service by itself. Packet traces are most useful when correlated with application logs and a precise test hypothesis.
Interpreting a static trace differs from managing a long-running capture. If a troubleshooting task needs live capture, document the authorization scope, BPF filters, capture limits, shutdown conditions and sensitive-data handling before collecting any traffic.
Summaries can still reveal private IP assignments and service ports. Before sharing a trace, sanitize it under the organization’s policy, keep an original only where authorized, and validate that filtering did not hide the failure mechanism. Avoid embedding real keys, passwords or sensitive requests inside tutorial examples.
Scapy becomes a useful learning tool when each layer explains a protocol role and every observation has a stated limitation. An offline synthetic object is enough to teach that foundation without risking unauthorized traffic.