A small demo of UDP messaging with a packet sniffer, written in Python.
It consists of three independent scripts:
client.py— splits a fixed text message into UDP packets and sends them to the server, then waits for the server to echo the message back line by line.server.py— receives the packets, reassembles the message, and echoes it back to the client one line at a time.sniffer.py— uses scapy to capture the UDP traffic exchanged between the client and the server on the loopback interface, printing each packet's source, destination, and payload.
Everything runs locally over UDP on 127.0.0.1:12321.
The client and server share a simple packet format:
+---------------------------+---+------------------------------+
| 4-digit sequence number | # | up to 95 characters of data |
+---------------------------+---+------------------------------+
- Each packet is at most
PACKET_SIZE(100) bytes: a 4-digit zero-padded sequence number, a#separator, and up to 95 characters of the message. - The sequence number counts down, so the last packet of a message carries
sequence number
0. The server keeps receiving packets until it sees sequence number0, at which point it knows the message is complete. - The server reassembles the message, splits it on newlines, and echoes each line back to the client as its own UDP datagram.
- The client reads back one datagram per line, waits 3 seconds, and repeats the whole exchange indefinitely.
Note: this is a teaching/demo project. It assumes packets arrive in order and without loss, which is reasonable over loopback but not guaranteed by UDP in general.
- Python 3
- scapy — only needed for
sniffer.py(client.pyandserver.pyuse the standard library only)
Install the sniffer dependency with:
pip install -r requirements.txtOpen separate terminals.
-
Start the server:
python3 server.py
-
Start the client:
python3 client.py
-
(Optional) Start the sniffer to watch the traffic. Capturing packets requires elevated privileges:
sudo python3 sniffer.py
Stop any of the scripts with Ctrl+C.
Client:
UDP target: 127.0.0.1:12321
client starts sending the message to the server
client sent packet no. 9
...
client sent packet no. 0
client finished sending the message to the server
client waits for the echoed lines from the server
client received line: Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
...
Server:
server listening on 127.0.0.1:12321
server received packet no. 9
...
server received packet no. 0
server received the full message from 127.0.0.1:53414
server starts echoing the message back line by line
server echoed: Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
...