Master Scapy: Send, Sniff, and Manipulate Network Packets with Python

This article introduces Python's Scapy library, explains what network packets are, lists common Scapy commands, demonstrates packet sniffing, crafting, sending, receiving, SYN scanning, serialization, and conversion techniques, and provides practical code examples for each operation.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Scapy: Send, Sniff, and Manipulate Network Packets with Python

Hello, I'm Huang Wei. Today we discuss Python's Scapy module for sending and receiving network packets.

Preface

Every time we browse the internet, many packets are sent and received in a continuous loop.

A packet (or data packet) is the basic unit of network communication, consisting of a header and a payload. The header contains fixed‑length fields such as source and destination addresses, while the payload carries the actual data.

1. Common Commands

ls() : List all supported packet fields. Example:

a = IP()
print(a.ls())

Use ls(ARP) or ls(tcp) to view fields of specific protocols. Note the case‑sensitivity: ls(ARP) works, ls(arp) does not.

lsc() : List all functions. lsc() hide_defaults() : Remove fields that have default values.

a = IP()
print(a.hide_defaults())

display() : Show current values of a packet's parameters.

a = IP()
a.display()

Other useful commands include show_interfaces(), str(pkt), hexdump(pkt), pkt.summary(), pkt.show(), pkt.sprintf(), pkt.command(), traceroute("baidu.com"), export_object(), import_object(), save_session(), load_session(), and fuzz().

2. Sniffing Packets

from scapy.all import *
pkt = sniff(iface="Realtek PCIe GBE Family Controller", count=3, filter='tcp', prn=lambda x: x.sprintf('{IP:%IP.src% -> %IP.dst%
}{Raw:%Raw.load%
}'))

Key parameters: filter: BPF filter expression iface: Network interface name count: Number of packets to capture prn: Callback function, often a lambda Examples:

# Capture TCP packets from 192.168.3.3 port 80
sniff(filter="ip src 192.168.3.3 and tcp and tcp port 80", prn=lambda x: x.summary())
# Capture packets destined for 192.168.0.0/24
sniff(filter="dst net 192.168", prn=lambda x: x.summary())
# Capture non‑ICMP packets
sniff(filter="not icmp", prn=lambda x: x.summary())

3. Crafting Packets

pkt = Ether()/IP(dst='192.168.1.2')/TCP(dport=80)

The OSI model layers and corresponding protocols are shown in the table below.

OSI Layer

TCP/IP Layer

Typical Protocols

Application

Application

HTTP, FTP, SMTP, etc.

Presentation

Application

Telnet, SNMP, Gopher

Session

Application

SMTP, DNS

Transport

Transport

TCP, UDP

Network

Network

IP, ICMP, ARP

Data Link

Data Link

Ethernet, PPP

Physical

Data Link

IEEE 802.11, etc.

4. Protocol Usage Examples

1) Build an IP packet

# Construct an IP packet with custom parameters
pkt = IP(dst="192.168.1.2", ttl=10)
ls(pkt)

Key fields: version, ihl, tos, len, id, flags, frag, ttl, proto, chksum, src, dst, options.

2) Build an ARP packet

# Construct an ARP request
arp_pkt = ARP(op=1, hwdst="ff:ff:ff:ff:ff:ff", pdst="192.168.1.1")
ls(ARP)

3) Build an Ethernet frame

# Construct Ethernet frame
eth = Ether(dst="ff:ff:ff:ff:ff:ff")
ls(Ether)

4) Build a TCP packet

# Construct TCP packet
tcp = TCP(sport=12345, dport=80, flags="S")
ls(TCP)

5. Sending and Receiving

1) Send only

send(pkt, inter=0, loop=0, count=1, iface='eth0')
# Layer‑3 send, no response
sendp(Ether()/IP(dst="www.baidu.com"))

2) Send and receive

# Layer‑3 send and receive
sr(IP(dst="www.baidu.com")/TCP(dport=[21,23,80], flags="S"))
sr1(IP(dst="www.baidu.com")/ICMP())
# Layer‑2 send and receive
srp(Ether()/IP(dst="www.baidu.com"))
srp1(Ether()/IP(dst="www.baidu.com"))

6. SYN Half‑Open Scan

Setting the TCP flag to S performs a SYN scan; a SYN/ACK reply indicates an open port, while an RST/ACK indicates a closed port.

sr1(IP(dst="192.168.1.2")/TCP(dport=80, flags="S"))

7. Serialization and Deserialization

Serialize a packet to a PCAP file and read it back:

pkt = Ether()/IP(dst='192.168.1.2')/TCP(dport=80)
wrpcap("hw.pcap", pkt)
pkts = rdpcap('hw.pcap')
print(pkts[0])

8. Packet‑String Conversion

zfc = str(pkts[0])
eth = Ether(zfc)

9. Base64 Export/Import

b64 = export_object(str(pkts[0]))
new_pkt = import_object(b64)

10. Offline Analysis

sniff(offline="hw.pcap")

Conclusion

Scapy provides a powerful, concise way to craft, send, sniff, and analyze network packets. With just a few commands you can perform complex tasks, saving development time. However, use this tool responsibly and never for malicious purposes.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

packet sniffingScapypacket craftingnetwork packets
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.