02: Socket Programming with Python
Course: Networking - Security Advanced · Updated: October 2026 Literature: K&R chapter 2 (Application Layer): "Socket Programming: Creating Network Applications" Related lab: Python Lab: UDP Pinger, with code in
UDPPingerServer.pyandUDP_Pinger_Client.py
Learning objectives
After studying this article you can:
- explain what a socket is and where it sits between the application and the transport layer
- write a simple UDP client and server in Python 3
- write a simple TCP client and server in Python 3
- explain the differences between UDP and TCP sockets in practice: connections, timeouts, message boundaries
- measure round-trip time and packet loss with a home-made "ping"
- recognise the security pitfalls of network code
1. What is a socket?
A socket is the interface (an API) between an application process and the transport layer. The application writes data into the socket, and the operating system's TCP/IP stack takes it from there.
1 2 3 4 5 6 7 | |
A socket is identified by:
- UDP: (destination IP address, destination port)
- TCP: the 4-tuple (source IP, source port, destination IP, destination port). That's why one web server on port 443 can handle thousands of clients at the same time.
In Python, sockets are created with the standard socket module:
| Constant | Meaning |
|---|---|
AF_INET / AF_INET6 |
IPv4 / IPv6 address family |
SOCK_DGRAM |
Datagram socket = UDP |
SOCK_STREAM |
Stream socket = TCP |
2. UDP: connectionless messages
With UDP:
- there is no handshake: you just send a datagram to an address
- every
sendto()is one message, and everyrecvfrom()returns one message (message boundaries are preserved) - there is no reliability: if a datagram is lost, the application has to notice (for example with a timeout)
2.1 The UDP Pinger server (modernised)
This is the server from the original lab, rewritten in current Python style. It drops about 30% of the packets on purpose to simulate a lossy network.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
Note on the 2018 code: the original server used
random.randint(0, 10)and dropped the packet if the value was< 4.randint(0, 10)returns 11 possible values, so the real loss rate was 4/11 ≈ 36%, not the 30% that the lab text claimed. Usingrandom.random() < 0.30makes the intent explicit.
2.2 The UDP Pinger client (modernised)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | |
Run it in two terminals:
1 2 | |
The main changes from the 2018 version:
| 2018 | 2026 | Why |
|---|---|---|
from socket import * |
import socket |
Avoids name collisions and makes the code clearer |
bare except: |
except TimeoutError: |
A bare except also hides real bugs and Ctrl+C |
time.time() |
time.perf_counter() |
A monotonic, high-resolution clock that is right for measuring intervals |
manual close() |
with socket.socket(...) |
The socket is always closed, even when an error occurs |
sys.argv |
argparse |
Input validation and a help text for free |
| string concatenation | f-strings | Easier to read |
3. TCP: connection-oriented byte streams
With TCP:
- the server has a listening socket (
listen()) and creates a new socket per client (accept()) - the client must
connect()first, which triggers the three-way handshake (see article 01) - data is a byte stream. One
send()does not match onerecv(), so the application has to define its own message boundaries (for example newline-separated text or a length prefix)
3.1 TCP echo server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
3.2 TCP client
1 2 3 4 5 6 | |
3.3 Handling many clients
The server above handles one client at a time. In practice you would use one of these:
- threads:
socketserver.ThreadingTCPServer asyncio: one thread, many connections (the modern approach for high concurrency)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
4. UDP vs TCP sockets: summary
UDP (SOCK_DGRAM) |
TCP (SOCK_STREAM) |
|
|---|---|---|
| Connection setup | None | connect() / listen() / accept() |
| Sending | sendto(data, addr) |
send() / sendall() |
| Receiving | recvfrom() returns the sender's address |
recv() |
| Message boundaries | Preserved | Not preserved (byte stream) |
| Reliability and order | No, so the application must handle it | Yes |
| Typical use | DNS, VoIP, games, streaming, QUIC | Web (HTTP/1.1, HTTP/2), mail, SSH, databases |
5. Observing your program in Wireshark
- Start Wireshark on the loopback interface (
loon Linux,Adapter for loopback traffic capture(Npcap) on Windows). - Use the filter
udp.port == 12000(UDP) ortcp.port == 12001(TCP). - Compare them. UDP traffic is just request/reply datagrams. TCP traffic shows SYN, SYN-ACK, ACK, then the data, then FIN.
References
Videos
- Jim Kurose: Socket programming (chapter 2 video lectures): https://gaia.cs.umass.edu/kurose_ross/lectures.php
- Corey Schafer: Python tutorials (Python basics): https://www.youtube.com/@coreyms
- Real Python: video courses on sockets and asyncio: https://realpython.com/
- NeuralNine: Python socket programming: https://www.youtube.com/@NeuralNine
Articles and documentation
- Python documentation,
socket: low-level networking interface: https://docs.python.org/3/library/socket.html - Python documentation, Socket Programming HOWTO: https://docs.python.org/3/howto/sockets.html
- Python documentation,
asynciostreams: https://docs.python.org/3/library/asyncio-stream.html - Real Python, Socket Programming in Python (Guide): https://realpython.com/python-sockets/
- Beej's Guide to Network Programming (C, but the classic explanation of the socket API): https://beej.us/guide/bgnet/
- K&R programming assignments (UDP Pinger, Web Server, SMTP client, etc.): https://gaia.cs.umass.edu/kurose_ross/programming.php
Tools
- Python 3.12 or newer: https://www.python.org/downloads/
netcat/ncat(test servers by hand:nc -u localhost 12000): https://nmap.org/ncat/- Wireshark: https://www.wireshark.org/
- Scapy (craft and send your own packets in Python): https://scapy.net/
Cyber Security
Why it matters
Every network service is ultimately a program that reads bytes from a socket. Those bytes come from untrusted sources. Many serious vulnerabilities come from network code that trusts its input:
- Buffer overflows and parsing bugs: in memory-unsafe languages, a malformed packet can lead to remote code execution (e.g. Heartbleed in OpenSSL, 2014, and many router/VPN appliance bugs in 2023–2025).
- Denial of Service: a server that blocks on one slow client, or allocates memory based on a length field the client controls, is easy to take down.
- UDP spoofing and amplification: a UDP server that sends a larger reply to a small request can be abused to attack third parties, because the source address of UDP can be forged.
- Information leakage: verbose error messages, debug ports and plaintext protocols reveal secrets.
- Security tooling: as a security professional you will write network tools yourself, such as scanners, honeypots, fuzzers and proof-of-concept exploits. Python and Scapy are the standard tools for this.
How to make it safe
- Validate all input: check lengths, types and formats. Never trust a length field from the client, and set maximum message sizes.
- Always use timeouts (
settimeout,create_connection(timeout=...)) and limit concurrent connections, so that slow or malicious clients can't hang your server. - Bind only where needed:
127.0.0.1for local tests, not0.0.0.0. Run services as an unprivileged user, never as root/Administrator. - Don't amplify: a UDP reply should be no larger than the request, unless the client has proved its address (QUIC does this with an address validation token).
- Encrypt: wrap TCP sockets with TLS using the
sslmodule (ssl.create_default_context().wrap_socket(...)) so that data can't be read or changed in transit (see article 13). - Never deserialise untrusted data with
pickle,marshaloreval(). Use JSON with schema validation. - Catch specific exceptions, and log errors without leaking internal details to the client.
- Prefer memory-safe languages for network-facing services (Python, Go, Rust). CISA and the NSA explicitly recommend moving away from C/C++ for new code.
- Test your server: fuzz it with malformed input (e.g.
boofuzz,AFL++) and scan it withnmap.
Extra references
- OWASP Input Validation Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html
- Python
sslmodule, Security considerations: https://docs.python.org/3/library/ssl.html#security-considerations - CISA, The Case for Memory Safe Roadmaps (2023): https://www.cisa.gov/resources-tools/resources/case-memory-safe-roadmaps
- Black Hat Python, 2nd ed. (Justin Seitz & Tim Arnold, No Starch Press, 2021): network tools for security testing in Python 3
- boofuzz (network protocol fuzzing): https://github.com/jtpereyda/boofuzz