Sub topic 7
The transport layer: TCP, UDP, and ports
This chapter assumes you know the four TCP/IP layers and how encapsulation wraps data in headers. It also assumes you can run Python and tcpdump in a terminal. The transport layer sits above the internet layer. It is where data stops being addressed to a host and starts being addressed to a program on that host.
What the transport layer adds
The internet layer delivers packets from one IP address to another. An IP address names a host, not a program, and a host runs many programs at once. A browser, an SSH client, and a DNS resolver may all be using the network at the same moment. The transport layer solves this with two features:
- Multiplexing and demultiplexing. The sender tags each segment or datagram with port numbers. The receiving operating system reads the destination port and hands the data to the right socket.
- Optional service on top of IP. IP is best-effort. Packets can be lost, duplicated, reordered, or delayed. UDP exposes that behavior almost unchanged. TCP hides it by adding reliability, ordering, flow control, and congestion control.
In OSI terms this is layer 4. The TCP/IP model has no separate layer numbering, but the transport layer maps to OSI layer 4 directly. This is one of the cleanest matches between the two models.
Ports and sockets
A port is a 16-bit number from 0 to 65535. IANA divides the range into three groups.
| Range | Name | Typical use |
|---|---|---|
| 0–1023 | Well-known (system) | Standard services such as HTTP on 80, HTTPS on 443, SSH on 22, DNS on 53 |
| 1024–49151 | Registered | Applications such as PostgreSQL on 5432 |
| 49152–65535 | Dynamic (ephemeral) | Source ports that the OS picks for outgoing connections |
Linux uses a different default ephemeral range, normally 32768–60999. You can read it from /proc/sys/net/ipv4/ip_local_port_range.
A server binds to a port and waits. A client does not choose a port. The OS assigns an ephemeral source port when the client connects or sends. A TCP connection is identified by five values: protocol, source IP, source port, destination IP, and destination port. This is why a web server on port 443 can serve thousands of clients. Each client connection has a different source address or source port, so each is a distinct connection.
TCP port 80 and UDP port 80 are separate namespaces. A program listening on TCP 53 does not receive UDP traffic for port 53.
UDP: a thin layer over IP
UDP (User Datagram Protocol) has an 8-byte header with four fields: source port, destination port, length, and checksum. It does nothing else.
- It has no connection setup. The first packet carries data.
- It does not retransmit lost datagrams, reorder them, or slow down when the network is congested.
- It preserves message boundaries. One
sendtocall produces one datagram, and onerecvfromcall returns one whole datagram. - Its checksum covers the header, the data, and a pseudo-header made of the IP addresses. A datagram that fails the checksum is dropped silently.
The application must handle loss itself, or tolerate it. That makes UDP a good fit for DNS queries, which are small and easy to retry. It also suits real-time audio and video, where a late packet is worthless. QUIC, the transport under HTTP/3, runs on UDP and builds its own reliability and encryption above it.
This program is the entire application side of a UDP send. The operating system adds the UDP, IP, and link-layer headers.
import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.sendto(b"hello", ("127.0.0.1", 9999))If nothing is bound to port 9999, the host answers with an ICMP "port unreachable" message. The sender's program does not see an error from this call. On a connected UDP socket, a later call may raise ConnectionRefusedError.
TCP: a reliable byte stream
TCP (Transmission Control Protocol) gives the application a reliable, ordered byte stream between two endpoints. Its header is at least 20 bytes. It includes the ports, a 32-bit sequence number, a 32-bit acknowledgment number, flag bits (SYN, ACK, FIN, RST, PSH, URG), a window size, and a checksum.
Connection setup
TCP opens a connection with a three-way handshake. Each side picks an initial sequence number and has it acknowledged.
Reliability and ordering
Every byte has a sequence number. The receiver acknowledges the next byte it expects. If the sender gets no acknowledgment before a retransmission timer expires, it sends the data again. Repeated duplicate acknowledgments also trigger a fast retransmit. The receiver uses sequence numbers to put out-of-order segments back in order and to discard duplicates.
Flow control and congestion control
These two mechanisms are often confused:
- Flow control protects the receiver. The receiver advertises a window, the amount of data it can buffer. The sender never has more unacknowledged data in flight than that window.
- Congestion control protects the network. The sender keeps a congestion window that grows while acknowledgments arrive and shrinks when loss suggests congestion. The sender is limited by the smaller of the two windows.
Closing
Each direction closes separately. One side sends FIN and the other acknowledges it, then the other side sends its own FIN. The side that closes first enters the TIME_WAIT state, usually for about 60 seconds on Linux. This prevents old segments from being mistaken for part of a new connection on the same address and port pair. An abrupt close uses RST, which tears the connection down immediately.
TCP is a stream, not messages
TCP does not preserve write boundaries. Two sendall calls may arrive as one recv, or one write may arrive in pieces. This script shows the effect. The server sleeps briefly so both writes have arrived before it reads.
import socket
import threading
import time
HOST, PORT = "127.0.0.1", 9000
def server(ready):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind((HOST, PORT))
srv.listen()
ready.set()
conn, addr = srv.accept()
with conn:
time.sleep(0.5)
data = conn.recv(4096)
print("server got", data, "from", addr)
ready = threading.Event()
t = threading.Thread(target=server, args=(ready,))
t.start()
ready.wait()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as c:
c.connect((HOST, PORT))
c.sendall(b"hello ")
c.sendall(b"world")
t.join()The server usually prints b'hello world' as one chunk, with the client's ephemeral port in addr. Applications that need messages must add their own framing, such as a length prefix or a delimiter. HTTP, for example, uses headers and a Content-Length or chunked encoding.
TCP and UDP compared
| Property | TCP | UDP |
|---|---|---|
| Connection | Handshake required | None |
| Delivery | Reliable, ordered | Best effort, may be lost or reordered |
| Data model | Byte stream | Discrete datagrams |
| Header size | 20 bytes or more | 8 bytes |
| Flow and congestion control | Yes | No |
| Unit of data | Segment | Datagram |
| Typical uses | HTTP/1.1 and HTTP/2, SSH, SMTP, databases | DNS queries, VoIP, games, QUIC |
Choose TCP when correctness matters more than latency and you do not want to write your own recovery logic. Choose UDP when you need low latency, small request and response exchanges, multicast or broadcast, or control over how loss is handled.
Seeing transport headers in a capture
This command captures five TCP packets on port 80. The -e option prints link-layer addresses, and -v prints IP and TCP header fields. The -nn option turns off name and port-name lookups so you see raw numbers.
sudo tcpdump -nn -e -v -c 5 'tcp port 80'In the output, the pair after each IP address (for example 192.0.2.10.80) is the port. Flags [S] is a SYN, [S.] is SYN-ACK, and [.] is a bare ACK. Look at seq and ack to follow the handshake from the diagram above. The win field is the advertised receive window.
You can also build the same stack of headers in Scapy. The / operator stacks layers from link to transport.
from scapy.all import Ether, IP, TCP
pkt = Ether() / IP(dst="192.0.2.10") / TCP(dport=80, flags="S")
pkt.show()The TCP block in the output shows the source port Scapy chose, destination port 80, sequence number, and the SYN flag.
Common errors and what they mean
- Connection refused. The host is reachable, but nothing listens on that port. The host answers a SYN with RST, so the failure is immediate.
- Connection timed out. The SYN got no reply. A firewall that drops packets, a wrong address, or a routing problem is the usual cause. The client retries the SYN with growing delays before giving up.
- Address already in use. A
bindfails because another process holds the port, or because connections in TIMEWAIT hold it. Servers usually set `SOREUSEADDR`, as the script above does. - Silent UDP loss. UDP gives no error when a datagram is dropped. Add timeouts, sequence numbers, and retries in the application.
- Wrong checksums in a capture. With checksum offload, the network card computes the checksum after the capture point.
tcpdumpon the sending host may then showincorrectchecksums on packets that are fine on the wire. - Truncated messages. Code that assumes one
recvreturns one message will fail under load. Loop until you have read a full frame.
Where the transport layer sits in the models
The transport layer is layer 4 in OSI and the third layer in the TCP/IP model. TCP and UDP are its main protocols. Ports belong here. TLS does not: it runs on top of TCP and is usually placed in the application layer of TCP/IP, even though some OSI diagrams show it near layers 5 and 6. A later chapter covers that blur.
Exercise
A client connects to a web server at 192.0.2.10 on port 443 from ephemeral port 51000. A second tab on the same client opens another connection to the same server and port. How does the server tell the two connections apart, and why does this not need a second listening port?
Show answer
The server identifies each connection by the full five values: protocol, source IP, source port, destination IP, and destination port. The second tab gets a different ephemeral source port, such as 51001, so the five values differ. Both connections share the single listening socket on port 443, and the OS demultiplexes incoming segments by the full set.
Exercise
Your program calls send twice on a TCP socket with 100 bytes each time. The peer calls recv(4096) once and gets 200 bytes. Is this a bug in TCP? What should the application do if it needs to treat the two writes as separate messages?
Show answer
It is not a bug. TCP delivers a byte stream and does not preserve write boundaries, so the two writes may arrive together. The application must add framing, for example by sending a length prefix before each message or ending each message with a delimiter, and then read until a complete message has arrived.
Exercise
A TCP connection attempt to a server fails instantly with "connection refused", while an attempt to a different server hangs for about 30 seconds and then times out. What does each symptom suggest about where the problem lies?
Show answer
An instant refusal means the packet reached a host that answered with RST, so the network path works and no process listens on that port. A long hang means the SYN got no answer, which points to a firewall silently dropping the packet, a wrong or unreachable address, or a routing fault. In the second case, check the path and firewall rules before you check the application.