CN/Lesson 5 of 8/7 min read
Transport Layer, TCP and UDP
Ports and sockets, multiplexing, UDP, TCP segment structure, three-way handshake, connection termination and TIME_WAIT, reliability, flow control, congestion control (slow start, AIMD, fast retransmit), and QUIC.
On this page
Transport Layer
The transport layer provides process-to-process (end-to-end) communication. The network layer gets a packet to the right host; the transport layer gets it to the right application on that host.
Responsibilities: multiplexing/demultiplexing via ports, segmentation and reassembly, and (for TCP) reliability, ordering, flow control and congestion control.
Port Number
A port number (16 bits, 0 to 65535) identifies an application endpoint on a host.
| Range | Name | Examples |
|---|---|---|
| 0 to 1023 | Well-known | 20/21 FTP, 22 SSH, 23 Telnet, 25 SMTP, 53 DNS, 80 HTTP, 110 POP3, 143 IMAP, 443 HTTPS |
| 1024 to 49151 | Registered | 3306 MySQL, 5432 PostgreSQL, 6379 Redis, 8080 HTTP alt |
| 49152 to 65535 | Dynamic / ephemeral | Client-side source ports |
Socket
A socket is an endpoint for communication: IP address + port. A TCP connection is uniquely identified by the 4-tuple (source IP, source port, destination IP, destination port), plus protocol. That is why one server port 443 can serve thousands of clients at once.
Server socket calls: socket(), bind(), listen(), accept(), recv()/send(), close(). Client: socket(), connect(), send()/recv(), close().
UDP
User Datagram Protocol: connectionless, unreliable, message oriented.
Header is only 8 bytes:
| Source port (16) | Destination port (16) |
| Length (16) | Checksum (16) |- No handshake, no acknowledgments, no retransmission, no ordering, no congestion control.
- Low latency and low overhead; supports broadcast and multicast.
- Used for DNS queries, DHCP, VoIP, video calls, online games, streaming, SNMP, and as the base of QUIC.
TCP
Transmission Control Protocol: connection oriented, reliable, ordered, byte stream, full-duplex, with flow and congestion control.
TCP header (20 to 60 bytes)
| Field | Purpose |
|---|---|
| Source / destination port | Process identification |
| Sequence number | Byte number of the first data byte in this segment |
| Acknowledgment number | Next byte expected from the other side (cumulative ACK) |
| Header length | Header size in 32-bit words |
| Flags | SYN, ACK, FIN, RST, PSH, URG (and ECE, CWR) |
| Window size | Receive window for flow control |
| Checksum | Header + data + pseudo-header |
| Urgent pointer | Rarely used |
| Options | MSS, window scale, SACK, timestamps |
Three-Way Handshake
Connection establishment:
Client Server
| -- SYN, seq = x ---------------> | (LISTEN -> SYN_RCVD)
| <-- SYN-ACK, seq = y, ack = x+1 - |
| -- ACK, ack = y+1 -------------> | (ESTABLISHED)- Both sides choose a random Initial Sequence Number (ISN), which defends against old duplicate segments and sequence prediction attacks.
- Options like MSS, window scaling and SACK are negotiated here.
- Why three and not two? Both sides must confirm the other received their ISN, and it prevents an old duplicate SYN from opening a stale connection.
SYN Flood
An attacker sends many SYNs (often with spoofed source IPs) and never completes the handshake, filling the server's half-open connection queue. Defense: SYN cookies (encode the state in the server's ISN so no memory is used until the final ACK), rate limiting, larger backlog. See DoS attacks.
Connection Termination
Four-way handshake (each direction is closed independently):
Client Server
| -- FIN -------------> | client: FIN_WAIT_1
| <-- ACK ------------- | client: FIN_WAIT_2, server: CLOSE_WAIT
| <-- FIN ------------- | server: LAST_ACK
| -- ACK -------------> | client: TIME_WAIT, server: CLOSEDA half-close is possible: one side finished sending but still receives. A RST aborts the connection immediately.
TIME_WAIT
The side that closes first waits in TIME_WAIT for 2 x MSL (maximum segment lifetime, typically 30 s to 2 min) before fully closing:
- So the final ACK can be retransmitted if it was lost.
- So delayed segments from the old connection die out before the same 4-tuple is reused.
Busy servers that close many connections can accumulate thousands of TIME_WAIT sockets; SO_REUSEADDR and connection reuse (keep-alive) help.
Reliability
TCP builds a reliable stream on top of unreliable IP:
- Sequence numbers order bytes and detect duplicates.
- Cumulative ACKs acknowledge all bytes up to a number; SACK (selective ACK) reports out-of-order blocks received.
- Retransmission timeout (RTO): computed from smoothed RTT and its variance; doubled on each timeout (exponential backoff).
- Checksum detects corruption.
TCP Flow Control
Flow control prevents the sender from overflowing the receiver's buffer.
- The receiver advertises a receive window (rwnd): free space in its buffer.
- The sender keeps
bytes in flight <= rwnd. - If
rwnd = 0, the sender stops and periodically sends window probes. - Window scaling option allows windows larger than 64 KB (needed for high bandwidth-delay paths).
Congestion Control
Congestion control prevents the sender from overwhelming the network. The sender keeps a congestion window (cwnd):
effective window = min(cwnd, rwnd)Slow Start
- Start with
cwnd= 1 to 10 MSS. - For every ACK,
cwnd += 1 MSS, so cwnd doubles every RTT (exponential growth). - Continue until cwnd reaches the slow start threshold (ssthresh).
AIMD
Additive Increase, Multiplicative Decrease (congestion avoidance phase):
- Above ssthresh, increase cwnd by about 1 MSS per RTT (linear).
- On loss, cut cwnd sharply.
This produces the classic sawtooth pattern and converges to fairness between flows.
Reaction to loss
| Event | TCP Tahoe | TCP Reno |
|---|---|---|
| Timeout | ssthresh = cwnd/2, cwnd = 1, slow start | Same |
| 3 duplicate ACKs | ssthresh = cwnd/2, cwnd = 1 | Fast recovery: cwnd = ssthresh (+3), continue linearly |
Fast Retransmit
Three duplicate ACKs strongly suggest one segment was lost while later ones arrived. The sender retransmits immediately without waiting for the timeout. With fast recovery (Reno) it does not drop back to slow start.
Modern algorithms: CUBIC (Linux default, cubic growth function, good for high bandwidth) and BBR (Google, models bottleneck bandwidth and RTT instead of reacting to loss).
Nagle's Algorithm
Nagle's algorithm reduces tiny packets: while there is unacknowledged data, buffer small writes and send them together. Combined with delayed ACKs it can add up to 200 ms latency for interactive apps, so latency-sensitive software sets TCP_NODELAY.
TCP vs UDP
| TCP | UDP |
|---|---|
| Connection oriented (handshake) | Connectionless |
| Reliable, ordered | Unreliable, unordered |
| Byte stream | Message (datagram) boundaries preserved |
| Flow and congestion control | None |
| 20 to 60 byte header | 8 byte header |
| Slower, more overhead | Fast, low overhead |
| HTTP/1.1, HTTP/2, SSH, SMTP, FTP | DNS, DHCP, VoIP, gaming, streaming, QUIC |
QUIC
QUIC is a transport protocol built on UDP, used by HTTP/3 (see application layer).
- Combines transport and TLS 1.3 handshakes: 1-RTT setup, 0-RTT resumption.
- Independent streams: a lost packet blocks only its stream, removing TCP's head-of-line blocking.
- Always encrypted, including most headers.
- Connection migration via connection IDs: switching from Wi-Fi to mobile data keeps the connection.
- Implemented in user space, so it evolves faster than kernel TCP.
Quick revision
- Connection = 4-tuple. Ports below 1024 are well-known.
- Handshake: SYN, SYN-ACK, ACK. Termination: FIN, ACK, FIN, ACK, then TIME_WAIT for 2 MSL.
- Flow control uses rwnd (receiver); congestion control uses cwnd (network).
- Slow start doubles per RTT up to ssthresh, then AIMD; 3 dup ACKs trigger fast retransmit.
- QUIC = UDP + TLS 1.3 + multiplexed streams, no head-of-line blocking.