Sub topic 6
Layer 4: Transport, TCP, UDP, and ports
This chapter assumes you know what an IP address is, that Layer 3 delivers packets from one host to another, and that you can run simple commands in a terminal. Layer 3 gets a packet to the right machine. Layer 4 gets the data to the right program on that machine, and it decides how reliable the delivery is.
What the transport layer does
The transport layer provides communication between processes, not just between hosts. It does this with three main tools:
- Ports: 16-bit numbers (0 to 65535) that identify a program on a host.
- Segmentation: splitting application data into pieces that fit the network.
- Optional reliability: acknowledgments, retransmission, ordering, and flow control.
The two main transport protocols are TCP and UDP. Applications pick one, and the choice shapes how the application behaves.
Ports and sockets
An IP address names a host. A port names a service or conversation on that host. Together they form an endpoint. A connection is identified by four values: source IP, source port, destination IP, and destination port. That is why one web server on port 443 can serve thousands of clients at once.
| Port range | Name | Typical use |
|---|---|---|
| 0–1023 | Well-known | HTTP 80, HTTPS 443, SSH 22, DNS 53 |
| 1024–49151 | Registered | Databases, application servers |
| 49152–65535 | Ephemeral | Temporary client-side ports chosen by the OS |
A client picks a random ephemeral source port for each connection. The server replies to that port.
TCP: reliable byte streams
TCP (Transmission Control Protocol) is connection-oriented. It gives the application an ordered, reliable stream of bytes. To do this it uses:
- Sequence numbers, so the receiver can reorder segments and detect gaps.
- Acknowledgments, so the sender knows what arrived.
- Retransmission of anything not acknowledged in time.
- Flow control, using a receive window so a fast sender does not overwhelm a slow receiver.
- Congestion control, which slows the sender when the network is overloaded.
Before any data moves, TCP sets up a connection with a three-way handshake.
The handshake costs one round trip before data is sent. Closing a connection uses FIN segments. A RST segment aborts one immediately, and you often see it when a port has no listening program.
UDP: simple datagrams
UDP (User Datagram Protocol) is connectionless. It adds only ports and an optional checksum to the data. There is no handshake, no retransmission, no ordering, and no congestion control. Each datagram stands alone and may be lost, duplicated, or reordered.
UDP is a good fit when speed matters more than perfect delivery, or when the application handles loss itself. DNS queries, voice and video calls, online games, and QUIC (the transport under HTTP/3) all use UDP.
| Feature | TCP | UDP |
|---|---|---|
| Connection setup | Three-way handshake | None |
| Delivery guarantee | Yes, with retransmission | No |
| Ordering | Preserved | Not preserved |
| Unit of data | Byte stream | Individual datagrams |
| Overhead | Higher (20-byte minimum header) | Lower (8-byte header) |
| Typical uses | Web, email, SSH, file transfer | DNS, streaming, games, QUIC |
Seeing Layer 4 in code
This program opens a TCP connection and sends a plain-text HTTP request. Your operating system performs the handshake, sequencing, and retransmission. Your code only sees a reliable stream.
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])create_connection triggers the handshake. recv(200) may return fewer bytes than requested, because TCP is a stream and does not preserve message boundaries. That is a common source of bugs. If you need a full message, loop on recv until you have it.
To check Layer 4 from the shell, test whether a TCP port accepts connections:
nc -zv example.com 443Success means the handshake completed. "Connection refused" usually means a RST came back because nothing listens on that port. A timeout usually means a firewall is silently dropping the packets.
Common errors
- Assuming UDP is broken when packets vanish. UDP offers no delivery guarantee, so the application must tolerate or handle loss.
- Treating TCP as message-based. One
senddoes not map to onerecv. - Confusing refused with timed out. Refused means the host answered and rejected. A timeout means no answer came back.
- Forgetting both protocols have separate port spaces. TCP port 53 and UDP port 53 are different endpoints.
Exercise
A client runs nc -zv server.example 8080 and gets "Connection refused" immediately. Another client gets no response for 30 seconds before timing out. What does each result suggest about Layer 4?
Show answer
"Connection refused" means the server host is reachable and replied with a TCP RST, so nothing is listening on port 8080 (or the service is bound to a different address). A 30-second timeout means the SYN got no reply, which usually points to a firewall dropping the packets or a routing problem at a lower layer.
Exercise
Why does a DNS lookup normally use UDP instead of TCP?
Show answer
A DNS query and its answer are each small and fit in one datagram. UDP avoids the cost of a handshake, so the lookup takes one round trip. If the answer is lost, the client simply asks again. DNS falls back to TCP only for large responses.