Part 3 · Ports, connections and names
TCP and UDP in depth: ports, sockets, handshakes and congestion
Course contents
So far, IP gets a packet to the right machine, on a best-effort basis: packets can be lost, duplicated or arrive out of order (lesson 1). This lesson is about the layer above, the transport layer, which does two more things: it delivers data to the right program on that machine, using ports, and, with TCP, it turns those unreliable packets into a reliable connection.
There are two transport protocols you need to know. UDP adds almost nothing to IP: ports, and that’s it. TCP adds a lot: a connection, ordering, retransmission of lost data, and control of the sending speed. You’ll see how each works, write small programs with both in Python, and watch them on the wire with tcpdump. This is also where everyday error messages like Connection refused and Connection reset by peer come from.
Ports and sockets
IP delivers a packet to a device; the transport layer delivers it to a process (a running program) on that device. It does this with a port: a 16-bit number from 0 to 65535. A server program asks the operating system for a port and waits on it; a client gets a temporary port of its own for each connection.
From inside a program, you use the network through a socket: an object the operating system gives you that stands for one end of a network conversation. You create one, tell it where to connect (or which port to wait on), and then read and write bytes through it, much like a file. Every language’s networking library, from Python’s socket module to an HTTP client, is built on sockets.
| Range | Name | Notes |
|---|---|---|
| 0–1023 | Well-known / System | Standard services (22, 53, 80, 443); binding needs root or a capability on Unix |
| 1024–49151 | Registered | Registered with IANA for software (3306 MySQL, 5432 Postgres, 6379 Redis) |
| 49152–65535 | Dynamic / Ephemeral | Temporary client-side ports (RFC 6335); Linux uses 32768 to 60999 by default |
A connection is identified by its 5-tuple: (Protocol, Source IP, Source Port, Destination IP, Destination Port). That is why a server on port 443 can hold millions of connections at once: each one comes from a different source IP and port.
ss -tlnp # listening (-l) TCP (-t) sockets, numeric (-n), with process (-p)
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 5 0.0.0.0:8000 0.0.0.0:* users:(("python3",pid=12347,fd=3))
0.0.0.0:8000 means this server listens on every interface; if it said 127.0.0.1:8000, it would be reachable only from the machine itself. The Process column tells you exactly which program holds the port, which makes ss the first command to reach for when you ask “who owns this port?”
ss -tanp state established # established TCP connections
cat /proc/sys/net/ipv4/ip_local_port_range # the ephemeral port range this machine uses
32768 60999
UDP: minimal and fast
UDP (RFC 768) adds little more than ports and a checksum on top of IP. Its header is 8 bytes: source port, destination port, length and checksum.
- Connectionless: there is no handshake; every
sendto()is an independent datagram. - No guarantees: a datagram can be lost, duplicated or arrive out of order. There is no flow control and no congestion control.
- Message boundaries are preserved: each
recvfrom()returns exactly one datagram (unlike TCP, which is a stream). - Used by: DNS, DHCP, NTP, VoIP and video calls, games, live streaming, and QUIC (the base of HTTP/3), which implements reliability and ordering itself, in user space.
- Keep datagrams smaller than the MTU (for example under 1200 bytes on the Internet) so they don’t get fragmented.
# udp_echo.py — run "python3 udp_echo.py server" in one terminal and "client" in another
import socket, sys
if sys.argv[1] == "server":
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("0.0.0.0", 9999))
while True:
data, addr = s.recvfrom(2048) # one datagram, plus who sent it
s.sendto(data.upper(), addr)
else:
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
c.settimeout(2) # UDP never tells you about loss: you need timeouts
c.sendto(b"hello", ("127.0.0.1", 9999))
print(c.recvfrom(2048))
(b'HELLO', ('127.0.0.1', 9999))
recvfrom returns both the data and the sender’s address (('127.0.0.1', 9999)), because in UDP there is no connection that “remembers” who the sender is; every datagram stands alone. Stop the server and run the client again: after 2 seconds it fails with timeout. UDP never tells you a message was lost. You have to set the timeout yourself.
TCP: a reliable stream over an unreliable network
TCP (RFC 9293) gives your program a two-way, ordered, error-free stream of bytes, on top of IP, which guarantees nothing. How can that work? The core idea fits in one example.
The idea: number every byte, confirm what arrived, resend what didn’t
TCP numbers every byte it sends; the number of the first byte in a segment is its sequence number. The receiver regularly replies with an acknowledgement (ACK): “I have everything up to byte N; send me N next.” Suppose the sender sends 3,000 bytes in three segments of 1,000:
sender receiver
seq 1 (bytes 1-1000) -------------> got it ACK 1001
seq 1001 (bytes 1001-2000) ----X lost
seq 2001 (bytes 2001-3000) -------------> a gap! ACK 1001 (again)
(no ACK for 2000 arrives in time, so resend)
seq 1001 (bytes 1001-2000) -------------> complete ACK 3001
The receiver keeps the out-of-order segment, waits for the missing one, and hands your program the bytes in order: your program never sees the gap. That is the whole trick behind reliability. Everything else in TCP is either the bookkeeping for this (the header below), getting it started and stopped (the handshake and closing), or deciding how fast to send (flow and congestion control).
Now the header that carries all of it:
| Field | Job |
|---|---|
| Source / Destination Port | The processes at each end |
| Sequence Number | Stream position of this segment’s first data byte (starts at a random ISN) |
| Acknowledgement Number | Next byte the receiver expects: “I have everything before this” (cumulative ACK) |
| Data Offset | Header length |
| Flags | SYN start, ACK ACK field valid, FIN done sending, RST abort, PSH, URG, ECE/CWR (ECN) |
| Window | Receiver’s free buffer space (flow control); up to 1 GB with Window Scale |
| Checksum | Covers header, data and a pseudo-header of the IP addresses |
| Options | MSS, Window Scale, SACK Permitted, Timestamps |
The three-way handshake
- Client:
SYN, seq=x(plus the MSS, Window Scale and SACK options). - Server:
SYN-ACK, seq=y, ack=x+1. - Client:
ACK, ack=y+1. Both sides are nowESTABLISHEDand data can flow (the client may already put data in this third packet).
The cost: one full RTT before the first byte of data. TCP Fast Open cuts this with a cookie, but it is rarely used; QUIC solves the problem at the root.
The ISN is random so that an attacker can’t slip a forged segment into an existing connection.
Closing a connection and TIME_WAIT
Each direction closes independently (a half-close):
- The side that closes first (
close()) sends aFINand moves toFIN_WAIT_1. - The other side ACKs it and moves to
CLOSE_WAIT. It can keep sending data until it callsclose()itself. - The second side sends its own
FIN(LAST_ACK). - The first side ACKs that and enters
TIME_WAIT, where it waits for a while (2 × MSL; a fixed 60 seconds on Linux). This keeps stray old segments from being mixed up with a new connection on the same 5-tuple, and lets it resend the last ACK if that ACK was lost.
RST means an immediate abort that skips all of the steps above: the port is closed, the process died, or a firewall or load balancer rejected the connection. That is where the Connection reset by peer message comes from.
| State | Meaning | If you see many of them |
|---|---|---|
LISTEN | Server waiting for connections | — |
SYN_SENT | Client sent a SYN and is waiting | The destination isn’t answering, or a firewall drops the SYN |
SYN_RECV | Server sent a SYN-ACK | A SYN flood, or the returning ACKs are lost |
ESTABLISHED | Connection open | — |
CLOSE_WAIT | The peer closed, your program hasn’t yet | A bug in your code: an unclosed socket or response body (a leak) |
TIME_WAIT | You closed first and are waiting | Normal; many on a client means you have no connection pooling |
Reliability: ACKs and retransmission
- The receiver uses ACKs to say how far it has received. If the sender gets no ACK within the RTO (retransmission timeout, based on the measured RTT), it resends the segment and doubles the RTO (exponential backoff).
- Fast retransmit: three duplicate ACKs mean one segment was lost but later ones arrived, so the missing segment is resent without waiting for the timeout.
- SACK (selective ACK): the receiver says exactly which blocks it has, so only the missing ones are resent.
Flow control: don’t drown the receiver
In the Window field, the receiver says how much room is left in its receive buffer (rwnd). The sender never keeps more unacknowledged data in flight than that. If the receiving program stops calling recv(), the window drops to zero and the sender stops (a zero window).
How big does the window need to be? Think of the link as a pipe: its bandwidth-delay product (BDP) is bandwidth × RTT, the amount of data “in the pipe” at any moment. On a 1 Gbps link with a 100 ms RTT, that is 10⁹ × 0.1 = 10⁸ bits, about 12.5 MB. To keep that pipe full, the sender must be allowed 12.5 MB of unacknowledged data in flight, so the window has to be at least that large; with a smaller window, the link never fills up, however fast it is. That is why the Window Scale option exists (the plain field only goes to 64 KB), and why Linux sizes the buffers automatically (autotuning).
Congestion control: don’t drown the network
Flow control protects the receiver; congestion control protects the network itself. The sender keeps a congestion window (cwnd), and the amount of data in flight is the smaller of cwnd and rwnd.
- Slow start: cwnd starts at about 10 segments (RFC 6928) and roughly doubles every RTT. So a fresh connection starts slowly. That is why short-lived connections never reach full bandwidth, and why connection reuse matters so much.
- When it reaches a threshold (ssthresh) or sees the first loss, it moves to congestion avoidance: linear growth (AIMD, additive increase and multiplicative decrease).
- When loss is detected, cwnd shrinks.
The algorithms: Reno (the classic), CUBIC (the default on Linux, Windows and macOS; RFC 9438), and Google’s BBR, which models bandwidth and RTT instead of reacting to loss, and does much better on links with random loss (such as wireless).
sysctl net.ipv4.tcp_congestion_control # the default algorithm for new connections
sysctl net.ipv4.tcp_available_congestion_control
net.ipv4.tcp_congestion_control = bbr
net.ipv4.tcp_available_congestion_control = reno bbr cubic
(On most machines the default is cubic; this one has been set to bbr.)
ss -ti dst example.com # per-connection rtt, cwnd, retransmits, congestion algo
Other mechanisms you should know
- Nagle’s algorithm: coalesces very small segments so that headers aren’t wasted. Combined with the receiver’s delayed ACK, it can add 40 to 200 ms of latency to interactive protocols. The fix is
TCP_NODELAY(every modern HTTP and database library sets it). - Keepalive: after a period of idleness, TCP sends probes to detect a dead connection or an expired NAT entry. The Linux default is 2 hours, far too long behind NAT and load balancers, so set it in your application or driver.
- Backlog: for every listening socket the kernel keeps two queues: the SYN queue (half-finished handshakes) and the accept queue (completed connections the program hasn’t
accept()ed yet). If the program accepts too slowly, the queue fills up and connections are dropped. - SYN flood: an attacker sends millions of SYNs from spoofed IPs to fill the SYN queue. The defense is SYN cookies (the state is encoded in the sequence number itself).
- Head-of-line blocking: because TCP is an ordered stream, losing one segment stalls delivery of all the data behind it until the retransmission arrives, even if that data belongs to other requests. This is the main reason QUIC was built.
- MSS (maximum segment size): the most data TCP puts in one segment so that the whole packet fits the MTU. On Ethernet that is 1,500 − 20 (IP header) − 20 (TCP header) = 1,460 bytes. Each side announces its MSS in its SYN. Routers in front of tunnels and VPNs often rewrite that value downwards in passing SYNs (MSS clamping), so that connections never send packets too big for the tunnel: the standard cure for the MTU black hole.
Socket programming
# tcp_echo.py — the whole lifecycle in a few lines
import socket, threading
def server():
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # rebind despite TIME_WAIT
srv.bind(("127.0.0.1", 9000))
srv.listen(128) # backlog
conn, addr = srv.accept() # blocks until a handshake completes
with conn:
while chunk := conn.recv(4096): # b"" = peer sent FIN
conn.sendall(chunk) # sendall loops until all bytes are queued
threading.Thread(target=server, daemon=True).start()
import time; time.sleep(0.2)
c = socket.create_connection(("127.0.0.1", 9000), timeout=3) # DNS + connect, with a timeout
c.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
c.sendall(b"hello over TCP")
print(c.recv(4096))
c.close() # sends FIN
What every network programmer should know:
- TCP has no messages, only a stream. Two
send()calls may arrive in a singlerecv(), and onesend()may be split across severalrecv()calls. Your own protocol has to mark where a message ends: with a length prefix, or with a delimiter (like\r\nin HTTP/1.1). send()may send only part of the data; usesendall()or a loop.- Always set timeouts for connect, read and write. Many libraries default to waiting forever.
SO_REUSEADDRlets a server bind again even though old connections are still in TIME_WAIT.SO_REUSEPORTlets several processes listen on the same port, with the kernel spreading the load between them.
Common errors and what they really mean
| Error | What it means on the network |
|---|---|
ECONNREFUSED (Connection refused) | Reached the host, but nothing listens on that port; the host sent an RST |
ETIMEDOUT (Connection timed out) | No reply at all: firewall drops the SYN, host down, or broken routing |
EHOSTUNREACH / ENETUNREACH | There is no route, or an ICMP Unreachable came back |
ECONNRESET (Connection reset by peer) | Mid-connection RST: process died, LB/NAT timeout, or writing after the peer closed |
EPIPE (Broken pipe) | Writing to a socket that has already received an RST |
EADDRINUSE (Address already in use) | The port is already taken (or in TIME_WAIT without SO_REUSEADDR) |
EADDRNOTAVAIL on the client | Ephemeral ports are exhausted (many connections to one destination without reuse) |