Skip to content
BoKSA

02: Socket Programming with Python

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.py and UDP_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
  Application process      Application process
        |  socket API              |  socket API
  +-----v------+            +------v-----+
  | TCP or UDP |  <------>  | TCP or UDP |      ← controlled by the OS
  |     IP     |  network   |     IP     |
  +------------+            +------------+
       Host A                    Host B

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 every recvfrom() 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
#!/usr/bin/env python3
"""UDP Pinger server: echoes messages in upper case, simulating ~30% packet loss."""
import random
import socket

HOST, PORT = "0.0.0.0", 12000
LOSS_RATE = 0.30

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server:
    server.bind((HOST, PORT))
    print(f"UDP Pinger server listening on {HOST}:{PORT}")
    while True:
        message, address = server.recvfrom(1024)
        if random.random() < LOSS_RATE:
            continue                      # pretend the packet was lost
        server.sendto(message.upper(), address)

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. Using random.random() < 0.30 makes 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
#!/usr/bin/env python3
"""UDP Pinger client: sends 10 pings and reports RTT and packet loss."""
import argparse
import socket
import time

parser = argparse.ArgumentParser(description="Simple UDP ping client")
parser.add_argument("host")
parser.add_argument("port", type=int)
parser.add_argument("-c", "--count", type=int, default=10)
parser.add_argument("-t", "--timeout", type=float, default=1.0)
args = parser.parse_args()

rtts = []
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client:
    client.settimeout(args.timeout)
    for seq in range(1, args.count + 1):
        message = f"Ping {seq} {time.strftime('%H:%M:%S')}"
        start = time.perf_counter()
        client.sendto(message.encode(), (args.host, args.port))
        try:
            reply, server = client.recvfrom(1024)
        except TimeoutError:              # Python 3.10+: socket.timeout is an alias of TimeoutError
            print(f"Request {seq} timed out")
            continue
        rtt_ms = (time.perf_counter() - start) * 1000
        rtts.append(rtt_ms)
        print(f"Reply from {server[0]}: {reply.decode()}  RTT={rtt_ms:.3f} ms")

lost = args.count - len(rtts)
print(f"\n--- statistics ---\n{args.count} sent, {len(rtts)} received, "
      f"{lost / args.count:.0%} loss")
if rtts:
    print(f"RTT min/avg/max = {min(rtts):.3f}/{sum(rtts) / len(rtts):.3f}/{max(rtts):.3f} ms")

Run it in two terminals:

1
2
python3 udp_pinger_server.py
python3 udp_pinger_client.py localhost 12000

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 one recv(), 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
#!/usr/bin/env python3
"""TCP server: receives a line of text and returns it in upper case."""
import socket

HOST, PORT = "0.0.0.0", 12001

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # allow quick restart (TIME_WAIT)
    server.bind((HOST, PORT))
    server.listen()
    print(f"TCP server listening on {HOST}:{PORT}")
    while True:
        conn, addr = server.accept()          # new socket for this client
        with conn:
            data = conn.recv(1024)
            if data:
                conn.sendall(data.upper())

3.2 TCP client

1
2
3
4
5
6
#!/usr/bin/env python3
import socket

with socket.create_connection(("localhost", 12001), timeout=5) as sock:
    sock.sendall(b"hello networking security\n")
    print(sock.recv(1024).decode())

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
import asyncio

async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    data = await reader.readline()
    writer.write(data.upper())
    await writer.drain()
    writer.close()
    await writer.wait_closed()

async def main() -> None:
    server = await asyncio.start_server(handle, "0.0.0.0", 12001)
    async with server:
        await server.serve_forever()

asyncio.run(main())

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

  1. Start Wireshark on the loopback interface (lo on Linux, Adapter for loopback traffic capture (Npcap) on Windows).
  2. Use the filter udp.port == 12000 (UDP) or tcp.port == 12001 (TCP).
  3. Compare them. UDP traffic is just request/reply datagrams. TCP traffic shows SYN, SYN-ACK, ACK, then the data, then FIN.

References

Videos

Articles and documentation

Tools


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

  1. Validate all input: check lengths, types and formats. Never trust a length field from the client, and set maximum message sizes.
  2. Always use timeouts (settimeout, create_connection(timeout=...)) and limit concurrent connections, so that slow or malicious clients can't hang your server.
  3. Bind only where needed: 127.0.0.1 for local tests, not 0.0.0.0. Run services as an unprivileged user, never as root/Administrator.
  4. 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).
  5. Encrypt: wrap TCP sockets with TLS using the ssl module (ssl.create_default_context().wrap_socket(...)) so that data can't be read or changed in transit (see article 13).
  6. Never deserialise untrusted data with pickle, marshal or eval(). Use JSON with schema validation.
  7. Catch specific exceptions, and log errors without leaking internal details to the client.
  8. 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.
  9. Test your server: fuzz it with malformed input (e.g. boofuzz, AFL++) and scan it with nmap.

Extra references