Part 3 · Ports, connections and names

TCP and UDP in depth: ports, sockets, handshakes and congestion

lesson 07 / 1929 min2 labspublished updated
Course contents
On this page
  1. Ports and sockets
  2. UDP: minimal and fast
  3. TCP: a reliable stream over an unreliable network
  4. Socket programming

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.

RangeNameNotes
0–1023Well-known / SystemStandard services (22, 53, 80, 443); binding needs root or a capability on Unix
1024–49151RegisteredRegistered with IANA for software (3306 MySQL, 5432 Postgres, 6379 Redis)
49152–65535Dynamic / EphemeralTemporary 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:

08162431Source PortDestination PortSequence NumberAcknowledgment NumberOffsetRsvdFlagsWindowChecksumUrgent PointerOptions (MSS, WScale, SACK, TS)Data
The TCP header is at least 20 bytes and grows to 60 with options.
FieldJob
Source / Destination PortThe processes at each end
Sequence NumberStream position of this segment’s first data byte (starts at a random ISN)
Acknowledgement NumberNext byte the receiver expects: “I have everything before this” (cumulative ACK)
Data OffsetHeader length
FlagsSYN start, ACK ACK field valid, FIN done sending, RST abort, PSH, URG, ECE/CWR (ECN)
WindowReceiver’s free buffer space (flow control); up to 1 GB with Window Scale
ChecksumCovers header, data and a pseudo-header of the IP addresses
OptionsMSS, Window Scale, SACK Permitted, Timestamps

The three-way handshake

ClientServerSYN seq=xSYN-ACK seq=y ack=x+1ACK ack=y+1both ESTABLISHED: data can flowdata seq=x+1 (100 bytes)ACK ack=x+101client calls close()FINACKFINACKclient: TIME_WAIT (60 s on Linux)
A connection opens with the three-way handshake, carries data, and closes with FIN.
  1. Client: SYN, seq=x (plus the MSS, Window Scale and SACK options).
  2. Server: SYN-ACK, seq=y, ack=x+1.
  3. Client: ACK, ack=y+1. Both sides are now ESTABLISHED and 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):

  1. The side that closes first (close()) sends a FIN and moves to FIN_WAIT_1.
  2. The other side ACKs it and moves to CLOSE_WAIT. It can keep sending data until it calls close() itself.
  3. The second side sends its own FIN (LAST_ACK).
  4. 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.

StateMeaningIf you see many of them
LISTENServer waiting for connections—
SYN_SENTClient sent a SYN and is waitingThe destination isn’t answering, or a firewall drops the SYN
SYN_RECVServer sent a SYN-ACKA SYN flood, or the returning ACKs are lost
ESTABLISHEDConnection open—
CLOSE_WAITThe peer closed, your program hasn’t yetA bug in your code: an unclosed socket or response body (a leak)
TIME_WAITYou closed first and are waitingNormal; 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.

  1. 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.
  2. When it reaches a threshold (ssthresh) or sees the first loss, it moves to congestion avoidance: linear growth (AIMD, additive increase and multiplicative decrease).
  3. 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 single recv(), and one send() may be split across several recv() calls. Your own protocol has to mark where a message ends: with a length prefix, or with a delimiter (like \r\n in HTTP/1.1).
  • send() may send only part of the data; use sendall() or a loop.
  • Always set timeouts for connect, read and write. Many libraries default to waiting forever.
  • SO_REUSEADDR lets a server bind again even though old connections are still in TIME_WAIT. SO_REUSEPORT lets several processes listen on the same port, with the kernel spreading the load between them.

Common errors and what they really mean

ErrorWhat 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 / ENETUNREACHThere 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 clientEphemeral ports are exhausted (many connections to one destination without reuse)