Sub topic 6
Layer 4: Transport, TCP, UDP, and ports
What this chapter assumes
You should know that Layer 3 (IP) delivers packets between hosts and that a packet carries source and destination IP addresses. You should also be comfortable running commands in a terminal. This chapter covers what Layer 4 adds on top of that, how TCP and UDP differ, and the errors you will meet most often.
The job of the transport layer
IP delivers a packet to a host. It does not say which program on that host should receive the data. It also makes no promise that the packet arrives, arrives once, or arrives in order.
The transport layer fills those gaps. It does two main things:
- Process-to-process delivery. It uses port numbers to hand data to the right program on the destination host.
- Delivery services. It optionally adds reliability, ordering, flow control, and congestion control.
Layer 4 runs only on the two end hosts. Routers in between normally look at the IP header and forward the packet without reading the TCP or UDP header. This is called end-to-end behavior.
The two protocols you will use in practice are TCP and UDP. Both are carried inside IP packets. The IP header has a protocol field: 6 means TCP, 17 means UDP.
Ports and sockets
A port is a 16-bit number from 0 to 65535 that identifies an endpoint on a host. A socket address is an IP address plus a port, written like 203.0.113.10:443.
Port ranges are a convention managed by IANA:
| Range | Name | Typical use |
|---|---|---|
| 0 to 1023 | Well-known ports | Standard services such as HTTP (80), HTTPS (443), SSH (22), DNS (53) |
| 1024 to 49151 | Registered ports | Specific applications, for example PostgreSQL (5432) |
| 49152 to 65535 | Dynamic or ephemeral ports | Temporary client-side ports |
Linux uses a different default ephemeral range, usually 32768 to 60999. You can check it with cat /proc/sys/net/ipv4/ip_local_port_range.
When a client connects to a web server, the client's operating system picks a random ephemeral source port. The server's destination port is the well-known one. A single TCP connection is identified by a four-tuple of values:
- Source IP address
- Source port
- Destination IP address
- Destination port
(The transport protocol is also part of the identity, so strictly it is a five-tuple.) This is why one server on port 443 can handle thousands of clients at once. Each client has a different source address or port, so each connection is distinct.
Choosing a port is a convention, not a security control. Running SSH on port 2222 does not change what the protocol is. It only changes where clients must look.
UDP: minimal transport
The User Datagram Protocol (UDP) adds only ports and an optional checksum to IP. Its header is 8 bytes:
| Field | Size |
|---|---|
| Source port | 2 bytes |
| Destination port | 2 bytes |
| Length | 2 bytes |
| Checksum | 2 bytes |
UDP is connectionless. There is no handshake. A program sends a datagram (the UDP data unit) and the network delivers it or drops it. UDP does not retransmit, reorder, or slow down when the network is busy. Message boundaries are preserved: one sendto call produces one datagram, and the receiver reads it as one unit.
UDP fits cases where speed or simplicity matters more than guaranteed delivery, or where the application handles loss itself:
- DNS queries (short request, short reply)
- Voice and video calls, where a late packet is worse than a lost one
- Online games
- QUIC, which builds its own reliable streams on top of UDP
Here is a complete UDP exchange you can run on one machine. Start the receiver first in one terminal:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.bind(("127.0.0.1", 9999))
data, addr = s.recvfrom(1024)
print("received", data, "from", addr)Then run the sender in a second terminal:
import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.sendto(b"hello", ("127.0.0.1", 9999))The receiver prints the message and the sender's address, including its ephemeral port. If you run the sender with no receiver listening, the send still succeeds. UDP does not tell the sender that nobody is there, although the host may return an ICMP "port unreachable" message.
TCP: reliable byte streams
The Transmission Control Protocol (TCP) gives applications a reliable, ordered byte stream. The application writes bytes and the receiver reads the same bytes in the same order. TCP hides loss, duplication, and reordering from the application.
Segments and the header
TCP data is split into segments, each carried in one IP packet. The TCP header is at least 20 bytes. Key fields:
- Source port and destination port (2 bytes each).
- Sequence number: the position in the stream of the first byte in this segment.
- Acknowledgment number: the next byte the sender of this segment expects to receive.
- Flags: SYN (start a connection), ACK (acknowledgment is valid), FIN (finish sending), RST (abort), PSH, and URG.
- Window size: how many more bytes the sender of this segment is willing to receive.
- Checksum: detects corruption in the header and data.
The three-way handshake
Before data flows, the two sides agree on starting sequence numbers.
The sequence numbers start at random values, not zero. This makes it harder for an attacker to inject segments and avoids confusion with old packets from earlier connections.
Reliability
TCP numbers every byte. The receiver sends acknowledgments saying how far it has received contiguously. If the sender does not get an acknowledgment within a retransmission timeout, it resends the data. Modern stacks also use duplicate acknowledgments and selective acknowledgments (SACK) to resend only what is missing, without waiting for the timeout.
Flow control and congestion control
These two mechanisms are often confused:
| Mechanism | Protects | How it works |
|---|---|---|
| Flow control | The receiver | The receiver advertises a window size. The sender never has more unacknowledged data in flight than that window. |
| Congestion control | The network | The sender keeps its own congestion window and grows it while things go well. It shrinks the window when it detects loss or delay. |
The sender is limited by the smaller of the two windows. A slow transfer on a fast link is often explained by a small receive window, a lot of packet loss, or a high round-trip time, since throughput is roughly window size divided by round-trip time.
Closing a connection
A normal close uses FIN segments in each direction. Each side closes its half of the stream independently, so a connection can be half-closed. An abrupt abort uses RST, which tears the connection down immediately and discards unsent data. After the active closer sends its final ACK, it stays in the TIME_WAIT state for a period, commonly 60 seconds on Linux. This lets it absorb late duplicate segments and re-send the last ACK if it was lost.
Connection states you will see
| State | Meaning |
|---|---|
| LISTEN | A server socket is waiting for connections |
| SYN_SENT | The client has sent SYN and is waiting for SYN-ACK |
| SYN_RECV | The server received SYN and replied, and is waiting for the final ACK |
| ESTABLISHED | The connection is open for data |
| FIN_WAIT, CLOSE_WAIT | The two sides are partway through closing |
| TIME_WAIT | The connection is closed and waiting out stray packets |
TCP versus UDP
| Property | TCP | UDP |
|---|---|---|
| Connection setup | Three-way handshake | None |
| Delivery guarantee | Retransmits lost data | None |
| Ordering | In order | None |
| Data model | Byte stream, no message boundaries | Datagrams, boundaries kept |
| Header size | 20 bytes or more | 8 bytes |
| Congestion control | Built in | None, the application must add it |
| Typical uses | Web, email, SSH, file transfer | DNS, media, games, QUIC |
The "no message boundaries" point catches many programmers. If a client calls send twice with 100 bytes each, the server's recv may return 200 bytes at once, or 50 and then 150. Applications on TCP must frame their own messages, for example with a length prefix or a delimiter such as HTTP's blank line.
Seeing Layer 4 in action
This TCP client sends a plain HTTP request and prints the status line. The operating system performs the handshake inside create_connection.
import socket
request = b"GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n"
with socket.create_connection(("example.com", 80), timeout=5) as s:
s.sendall(request)
data = s.recv(200)
print(data.decode("ascii", errors="replace").splitlines()[0])Note that recv(200) returns up to 200 bytes. For a longer response you would loop until recv returns an empty bytes object, which means the peer closed its side.
To inspect sockets on a Linux host, use ss:
ss -tan # TCP sockets, all states, numeric addresses
ss -uan # UDP sockets, numeric
ss -ltnp # TCP listeners and the processes that own themTo test a port from the outside:
nc -zv example.com 443 # TCP: does a connection succeed?
nc -zvu 192.0.2.10 53 # UDP: unreliable result, see belowCommon errors and what they mean
Different failures at Layer 4 look different from the client side. Learning to tell them apart saves a lot of time.
| Symptom | Likely cause |
|---|---|
| "Connection refused" immediately | The host answered with RST because no program listens on that port. The network path works. |
| "Connection timed out" after a long wait | SYN packets get no reply. A firewall is silently dropping them, the host is down, or routing is broken. |
| Connects, then stalls or resets | An application problem, a firewall idle-timeout, or a middlebox dropping state |
| Many sockets in TIME_WAIT | Many short-lived connections from one host. This is normal, but can exhaust ephemeral ports under heavy load. |
| Growing CLOSE_WAIT sockets | The remote side closed but the local application never called `close`. This is usually an application bug. |
| "Address already in use" on server start | Another process holds the port, or the previous server's socket is still in TIME_WAIT. Set `SO_REUSEADDR` before binding. |
Edge cases worth knowing
- Fragmentation and size. A UDP datagram larger than the path MTU (commonly 1500 bytes of IP packet) is fragmented at IP, and losing any fragment loses the whole datagram. TCP avoids this by negotiating a maximum segment size (MSS) during the handshake.
- SYN floods. An attacker sends many SYN packets and never completes the handshake, filling the server's half-open connection queue. SYN cookies are a common defense.
- Nagle's algorithm and delayed ACKs. TCP may hold back small writes to batch them. Latency-sensitive programs sometimes set
TCP_NODELAYto turn this off. - Checksums. They catch accidental corruption, not tampering. Integrity against an attacker needs TLS, which sits above TCP.
- Head-of-line blocking. Because TCP delivers bytes in order, one lost segment delays everything behind it, even data that has already arrived. This is one motivation for QUIC.
Where Layer 4 sits in the model
Layer 4 receives data from the session, presentation, or application layers above and wraps it in a TCP segment or UDP datagram. It passes that unit down to Layer 3, which adds IP addressing. On the receiving host, Layer 3 passes the payload up and the destination port selects the receiving program. In the TCP/IP model, the transport layer maps directly to Layer 4 of OSI.
Exercise
A client program gets "Connection refused" instantly when connecting to a server on port 8080, but "Connection timed out" after about two minutes when connecting to the same server on port 9090. Explain what each result suggests about the server, the network, and any firewall.
Show answer
"Connection refused" on 8080 means a TCP RST came back quickly. The server host is reachable and the path works, but no program is listening on port 8080 (or a firewall actively rejects it with a reset). "Connection timed out" on 9090 means the SYN got no reply at all. The most likely cause is a firewall silently dropping packets to port 9090, though a downed host or routing fault is possible. Since 8080 got a reply from the same host, the host and path are probably up, which points to a firewall rule on 9090.
Exercise
A client sends two 100-byte messages over one TCP connection, one right after the other. The server calls recv(1024) once and gets 200 bytes. Is this a bug in TCP? How should the application tell the two messages apart?
Show answer
It is not a bug. TCP provides a byte stream with no message boundaries, so segments may be merged or split. The application must add framing, for example a length prefix before each message, a fixed message size, or a delimiter. The receiver then loops on recv until it has read a complete message. UDP would keep the two messages separate, but gives no delivery guarantee.
Exercise
A download runs slowly over a link with a 100 ms round-trip time. The receiver advertises a 64 KB window. Roughly what is the maximum throughput, and what two changes could raise it?
Show answer
Throughput is about window divided by round-trip time: 64 KB / 0.1 s = 640 KB/s, or about 5 Mbit/s. Raising it needs a larger receive window (TCP window scaling and larger buffers) or a lower round-trip time (a closer server). Reducing packet loss also helps, because loss shrinks the congestion window.