Sub topic 13
TCP and UDP in code with sockets
This chapter assumes you know the layered network model, what an IP address and a port are, and basic Python. It shows how the TCP and UDP behaviour from earlier chapters appears in the sockets API, and where programs go wrong when they ignore it.
The same API, two different contracts
A socket is the operating system's handle for one end of a communication channel. You create it with socket.socket(family, type). The type selects the transport protocol: SOCK_STREAM gives TCP and SOCK_DGRAM gives UDP. The calls that follow differ because the guarantees differ.
| Step | TCP (`SOCK_STREAM`) | UDP (`SOCK_DGRAM`) |
|---|---|---|
| Server setup | `bind`, `listen`, `accept` | `bind` |
| Client setup | `connect` (runs the three-way handshake) | none required |
| Send | `send` or `sendall` | `sendto` |
| Receive | `recv` returns some bytes, with no boundaries | `recvfrom` returns one whole datagram and the sender's address |
| End of data | `recv` returns `b""` after the peer closes | no signal exists |
| Loss | hidden by retransmission | silent, so you need a timeout |
A TCP echo server
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 9000))
srv.listen()
conn, addr = srv.accept()
with conn:
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)Each call has a specific job:
bindattaches the socket to a local address and port. Port 9000 is now reserved for this socket.listenmarks the socket as a passive listener. The kernel then completes handshakes on its behalf and queues finished connections.acceptblocks until a queued connection exists. It returns a second socket,conn, for that one peer. The listening socket stays open for more clients. This is multiplexing by the four-tuple of source and destination address and port.SO_REUSEADDRlets you restart the server right away. Without it,bindcan fail with "Address already in use" while old connections sit inTIME_WAIT.recv(1024)returns up to 1024 bytes. An empty bytes object means the peer closed its sending direction. It is not an error.
This server handles exactly one client and then exits. A real server would loop on accept and hand each conn to a thread, a process, or an event loop such as selectors or asyncio.
A TCP client and the byte stream
import socket
with socket.create_connection(("127.0.0.1", 9000)) as s:
s.sendall(b"hello ")
s.sendall(b"world")
s.shutdown(socket.SHUT_WR)
chunks = []
while True:
data = s.recv(1024)
if not data:
break
chunks.append(data)
print(b"\".join(chunks))create_connection resolves the name, creates the socket, and calls connect. When it returns, the handshake is done. The two sendall calls are two writes, but TCP is a byte stream. The server may see hello world in one recv or in several pieces, and the echo comes back with the same freedom. Only the order of the bytes is guaranteed.
shutdown(SHUT_WR) sends a FIN, so the server's recv returns b"" and its loop ends. The client can still read. This half-close is how the client says "I am finished sending" while it waits for the rest of the reply. A plain close would give up the read side too.
Mistakes that come from the byte stream
- Assuming one
recvequals onesend. This works on a quiet loopback and fails under load or across a real network. - Using
sendand ignoring its return value.sendmay accept only part of the buffer and returns the count.sendallloops until everything is queued or an error is raised. - Treating
recvas a loop condition on a fixed size.recv(n)can return fewer thannbytes at any time. - Never reading
b"". If you ignore it, you loop forever on a closed connection.
Framing: restoring message boundaries
When your protocol has messages, you must mark them yourself. The two common methods are a delimiter such as a newline, and a length prefix. The length prefix is binary-safe, so this example uses it.
import socket
import struct
def recv_exact(sock, n):
buf = bytearray()
while len(buf) < n:
chunk = sock.recv(n - len(buf))
if not chunk:
raise ConnectionError("peer closed in the middle of a message")
buf.extend(chunk)
return bytes(buf)
def send_msg(sock, payload):
sock.sendall(struct.pack("!I", len(payload)) + payload)
def recv_msg(sock):
(length,) = struct.unpack("!I", recv_exact(sock, 4))
return recv_exact(sock, length)
a, b = socket.socketpair()
with a, b:
send_msg(a, b"hello ")
send_msg(a, b"world")
print(recv_msg(b), recv_msg(b))This prints b'hello ' b'world'. The socketpair call gives two connected stream sockets in one process, which is enough to test framing without a network. The !I format means a 4-byte unsigned integer in network (big-endian) byte order. In production, also cap length so a corrupt or hostile prefix cannot make you allocate gigabytes.
UDP: datagrams without a connection
UDP needs no listen, accept or connect. Run the server in one terminal and the client in another.
# udp_server.py
import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as srv:
srv.bind(("127.0.0.1", 9001))
data, addr = srv.recvfrom(2048)
srv.sendto(data, addr)# udp_client.py
import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as cli:
cli.settimeout(2)
cli.sendto(b"ping", ("127.0.0.1", 9001))
try:
reply, _ = cli.recvfrom(2048)
print(reply)
except socket.timeout:
print("no reply")Start the server first. If the client runs alone, it prints no reply after two seconds, because UDP does not report that nobody was listening.
Key differences from TCP:
- Message boundaries survive. Each
sendtois one datagram, and eachrecvfromreturns one whole datagram. Two sends ofb"hello "andb"world"arrive as two reads, never merged. - The address comes with every read. One UDP socket serves many peers, so
recvfromtells you who sent each datagram. You reply withsendto(data, addr). - The buffer size is a limit. If a datagram is larger than the buffer you pass to
recvfrom, the excess is usually discarded without an error. A UDP payload can be up to 65,507 bytes over IPv4, so size buffers for your largest message. - Loss, duplication and reordering are your problem. Nothing retransmits. Use a timeout, and if you need reliability, add sequence numbers and retries in the application.
- Keep datagrams below the path MTU. A datagram larger than about 1,472 bytes of payload on Ethernet gets fragmented by IP, and losing any fragment loses the whole datagram. Many applications stay under roughly 1,200 bytes.
Connected UDP sockets
You may call connect on a UDP socket. No packets are sent. The kernel only records a default peer. After that you can use send and recv, and the socket drops datagrams from other addresses. It also lets the OS report an ICMP "port unreachable" as ConnectionRefusedError on a later call. An unconnected socket usually gets no such error.
Common failures and their meaning
| Symptom | Likely cause |
|---|---|
| `ConnectionRefusedError` on `connect` | Nothing is listening on that port, so the host answered with a reset |
| `TimeoutError` or a long hang on `connect` | Packets are dropped, for example by a firewall |
| `OSError: Address already in use` on `bind` | Another process holds the port, or old connections are in `TIME_WAIT` and `SO_REUSEADDR` is missing |
| `ConnectionResetError` on `recv` or `send` | The peer closed with unread data or sent a RST |
| `BrokenPipeError` on `send` | You wrote after the peer fully closed |
| `recv` blocks forever | No data and no close arrived, and no timeout was set |
Set a timeout with settimeout on any socket that talks to a network you do not control. A blocking call with no timeout is a hang waiting to happen.
Exercise
A TCP client calls sendall(b"AAAA") and then sendall(b"BBBB"). The server's first recv(1024) returns b"AAAABB". Is this a bug in TCP, and what should the server do to read 4-byte messages correctly?
Show answer
It is not a bug. TCP is a byte stream and keeps byte order but not write boundaries, so a single recv can return any amount of data up to the buffer size. The server should read exactly 4 bytes per message, looping on recv(4 - len(buf)) until it has them, as recv_exact does. It should treat b"" as the peer closing, and raise an error if that happens mid-message.
Exercise
A UDP client sends one datagram and calls recvfrom without a timeout. The server is not running. Why can the client hang forever, and how does connecting the UDP socket change this?
Show answer
UDP gives no delivery report, so the client cannot tell a lost datagram from a slow reply and recvfrom waits indefinitely. If the client first calls connect on the socket, the kernel can deliver the ICMP "port unreachable" message as ConnectionRefusedError, so the failure appears quickly on some systems. A timeout is still the reliable fix, because ICMP can be filtered or never sent.