Sub topic 6
Transport Layer: Ports and the TCP or UDP Header
This chapter assumes you know how encapsulation wraps application data in headers, what an IP address is, and how to read hexadecimal bytes. It covers the transport layer: what the layer adds to application data, how ports work, and what the TCP and UDP headers contain.
What the transport layer adds
The network layer delivers a packet to a host, identified by an IP address. A host runs many programs at once, such as a browser, a mail client and a DNS resolver. The transport layer decides which program receives the data.
It does this with ports. A port is a 16-bit number, from 0 to 65535, written in the transport header. The operating system keeps a table that maps each port to a socket owned by one process. When a segment arrives, the system reads the destination port and hands the payload to that socket.
Two protocols dominate this layer:
- UDP (User Datagram Protocol) adds ports and an optional checksum. It sends each message as an independent datagram.
- TCP (Transmission Control Protocol) adds ports, sequence numbers, acknowledgements, flow control and connection state. It presents the application with a reliable, ordered byte stream.
How ports are used
A server binds to a fixed, well-known port so clients can find it. A client does not choose a port. The operating system assigns it a temporary one, called an ephemeral port, for the lifetime of the connection.
| Range | Name | Typical use |
|---|---|---|
| 0–1023 | Well-known (system) | HTTP 80, HTTPS 443, SSH 22, DNS 53 |
| 1024–49151 | Registered | Databases and other named services |
| 49152–65535 | Dynamic (ephemeral) | Client-side ports assigned by the OS |
The IANA ranges above are a convention. Linux, for example, picks ephemeral ports from 32768–60999 by default. You can read the range from /proc/sys/net/ipv4/ip_local_port_range.
One port does not identify a connection. A TCP connection is identified by four values together: source IP, source port, destination IP and destination port. Together with the protocol, these form the 5-tuple. A web server on port 443 can therefore hold thousands of connections at once. Each client arrives with a different source address or source port, so each combination is distinct.
TCP port 80 and UDP port 80 are separate namespaces. The IP header's protocol field (6 for TCP, 17 for UDP) tells the receiver which transport handles the segment first.
The UDP header
The UDP header is 8 bytes, fixed.
| Field | Size | Meaning |
|---|---|---|
| Source port | 16 bits | Sender's port. May be 0 if no reply is expected. |
| Destination port | 16 bits | Port of the receiving service. |
| Length | 16 bits | Header plus data, in bytes. Minimum 8. |
| Checksum | 16 bits | Error check over a pseudo-header, the UDP header and the data. |
UDP has no connection state, no retransmission and no ordering. If a datagram is lost, UDP does not notice. DNS queries, streaming media, and protocols such as QUIC use UDP for this reason: they either tolerate loss or implement their own recovery.
In IPv4, a checksum of 0 means "not computed". In IPv6 the checksum is mandatory.
The TCP header
The TCP header is at least 20 bytes. Options can extend it to 60.
| Field | Size | Meaning |
|---|---|---|
| Source port | 16 bits | Sender's port. |
| Destination port | 16 bits | Receiver's port. |
| Sequence number | 32 bits | Position of the first data byte in this segment, within the sender's byte stream. |
| Acknowledgement number | 32 bits | Next byte the sender of this segment expects to receive. Valid when ACK is set. |
| Data offset | 4 bits | Header length in 32-bit words. 5 means 20 bytes. |
| Reserved | 3 bits | Must be zero. |
| Flags | 9 bits | NS, CWR, ECE, URG, ACK, PSH, RST, SYN, FIN. |
| Window | 16 bits | How many bytes the sender of this segment can accept right now (flow control). |
| Checksum | 16 bits | Error check over a pseudo-header, the header and the data. |
| Urgent pointer | 16 bits | Used only when URG is set. Rarely used. |
The key behaviors are these:
- Sequence numbers count bytes, not segments. If a segment starts at sequence 1000 and carries 500 bytes, the next segment starts at 1500. The receiver acknowledges 1500 to say it has everything before that.
- The data offset tells you where the payload starts. Do not assume 20 bytes. A SYN segment usually carries options, such as the MSS option, so its header is often 32 bytes or more.
- The flags control the connection. SYN opens a connection, FIN closes it gracefully, RST aborts it, ACK confirms received data, and PSH asks the receiver to pass data to the application promptly.
- The window field is 16 bits, so it caps at 65535 bytes. The window scale option, negotiated in the handshake, multiplies it for fast, long paths.
- The checksum uses a pseudo-header. The calculation includes the source and destination IP addresses, the protocol number and the segment length, even though those fields live in the IP header. This catches segments delivered to the wrong host.
Opening a connection
TCP sets up shared state before any application data moves. The three-way handshake exchanges initial sequence numbers and options such as the MSS.
A SYN consumes one sequence number even though it carries no data. That is why the server acknowledges x+1.
Parsing the headers in Python
The following program builds a TCP SYN segment, a TCP data segment and a UDP datagram, then decodes each one. It uses network byte order (!) because all header fields are big-endian.
import struct
TCP_FLAGS = [
(0x01, "FIN"), (0x02, "SYN"), (0x04, "RST"), (0x08, "PSH"),
(0x10, "ACK"), (0x20, "URG"), (0x40, "ECE"), (0x80, "CWR"),
]
def parse_tcp(segment):
sport, dport, seq, ack, off_flags, window, checksum, urgent = \
struct.unpack("!HHIIHHHH", segment[:20])
header_len = (off_flags >> 12) * 4
flags = [name for bit, name in TCP_FLAGS if off_flags & bit]
return {
"sport": sport, "dport": dport, "seq": seq, "ack": ack,
"header_len": header_len, "flags": flags, "window": window,
"payload": segment[header_len:],
}
def parse_udp(datagram):
sport, dport, length, checksum = struct.unpack("!HHHH", datagram[:8])
return {
"sport": sport, "dport": dport, "length": length,
"payload": datagram[8:length],
}
# SYN: data offset 5 (20 bytes), flag SYN = 0x002, no payload
syn = struct.pack("!HHIIHHHH", 50000, 80, 1000, 0, (5 << 12) | 0x002, 65535, 0, 0)
# Data segment: flags PSH + ACK = 0x018, carries 5 bytes
data = struct.pack("!HHIIHHHH", 50000, 80, 1001, 7000, (5 << 12) | 0x018, 65535, 0, 0) + b"hello"
# UDP datagram: length = 8-byte header + 5 bytes of data
udp = struct.pack("!HHHH", 53000, 53, 8 + 5, 0) + b"hello"
print(parse_tcp(syn))
print(parse_tcp(data))
print(parse_udp(udp))The second TCP segment prints flags: ['PSH', 'ACK'] and payload: b'hello'. The UDP result shows length: 13, which counts the header as well as the data.
To see real connections and their ports on a Linux machine, run:
ss -tnEach line lists the local address and port, then the peer address and port. Together they are the four values that identify the connection.
Common errors
- Reading the payload at a fixed offset. If you slice at byte 20, you will include TCP options in the payload whenever the header is longer. Always compute the offset from the data offset field.
- Using little-endian unpacking. Header fields are big-endian. Python's
structneeds!or>, otherwise port 80 appears as 20480. - Treating the UDP length as payload length. It includes the 8-byte header.
- Expecting UDP to preserve nothing but boundaries. UDP keeps message boundaries, so one send is one datagram. TCP does not. Two sends can arrive as one read, or one send as two reads. Applications must frame their own messages over TCP.
- Confusing a closed port with a filtered port. If nothing listens on a TCP port, the host replies with RST, and the client sees "connection refused". If a firewall drops the SYN silently, the client sees a timeout instead.
- Port already in use. Only one socket can bind a given local address, port and protocol, unless special options such as
SO_REUSEADDRorSO_REUSEPORTare set.
Choosing between TCP and UDP
Use TCP when the application needs every byte, in order, and can accept the cost of the handshake and retransmission delay. Web pages, file transfer and email fit this. Use UDP when the application handles loss itself or prefers fresh data to complete data. Voice calls, DNS lookups and game state updates fit this.
Exercise
A TCP segment has a data offset field of 8 and a sequence number of 5000. It carries 400 bytes of payload. How long is the TCP header in bytes, and what acknowledgement number does the receiver send back if it accepts all 400 bytes?
Show answer
The header is 8 × 4 = 32 bytes, because the data offset counts 32-bit words. The sequence number counts payload bytes, so the segment covers bytes 5000 through 5399. The receiver acknowledges 5400, the next byte it expects.
Exercise
A client opens two simultaneous connections to the same web server at 203.0.113.5 port 443. Both come from IP 192.168.1.10. How does the server's operating system tell the connections apart, and which header field must differ?
Show answer
A connection is identified by the source IP, source port, destination IP and destination port. The IPs and the destination port are the same here, so the source port must differ. The client's operating system assigns a different ephemeral port to each connection, and the server uses that port to deliver each segment to the right socket.