Sub topic 6
TCP segments and the TCP header
This chapter assumes you know the layered model (application, transport, network, link), what an IP packet is, and basic Python. Earlier chapters covered ports, sockets, and the split between connection-oriented and connectionless delivery. Here we look at the unit TCP sends, the segment, and at every field in its header.
What a segment is
TCP gives applications a byte stream, but it cannot put a stream on a wire. It cuts the stream into pieces, and each piece travels as one segment. A segment is a TCP header followed by a chunk of application data (the payload). The segment is then handed to IP as the payload of an IP packet.
A segment can have an empty payload. The handshake segments and many pure acknowledgments carry only a header.
The largest payload in one segment is the maximum segment size (MSS). It is negotiated during the handshake. On Ethernet the link MTU is usually 1500 bytes. Subtract 20 bytes for the IPv4 header and 20 for the minimal TCP header, and the MSS is 1460 bytes. IPv6 has a 40-byte base header, so its MSS is typically 1440.
The fixed header
The fixed part of the header is 20 bytes. All multi-byte fields are in network byte order (big-endian).
| Field | Size | Purpose |
|---|---|---|
| Source port | 16 bits | Sender's port, so replies can return to the right socket |
| Destination port | 16 bits | Port of the receiving application |
| Sequence number | 32 bits | Position in the byte stream of the first payload byte |
| Acknowledgment number | 32 bits | Next byte the sender of this segment expects to receive |
| Data offset | 4 bits | Header length in 32-bit words |
| Reserved | 4 bits | Unused (one bit was later taken for the NS flag) |
| Flags | 8 bits | CWR, ECE, URG, ACK, PSH, RST, SYN, FIN |
| Window | 16 bits | How many more bytes the sender of this segment will accept |
| Checksum | 16 bits | Detects corruption of header, payload, and addressing |
| Urgent pointer | 16 bits | Offset of urgent data, meaningful only with URG |
Compare this with UDP's 8-byte header, which has only ports, length, and checksum. Every extra TCP field exists to support something UDP does not offer: ordering, reliability, flow control, or connection state.
Ports
The source and destination ports, combined with the source and destination IP addresses, identify a connection. This four-value tuple is how a server with one listening port on 443 can hold thousands of separate connections at once. Each client has a different address or source port.
Sequence and acknowledgment numbers
TCP numbers bytes, not segments. The sequence number is the stream position of the first payload byte in the segment. The acknowledgment number is cumulative: it names the next byte the receiver wants, which means "I have everything before this."
If a segment has sequence number 1000 and carries 500 bytes, it covers bytes 1000 to 1499. The receiver acknowledges it with acknowledgment number 1500.
Two special cases catch people out. The SYN and FIN flags each consume one sequence number, even though they carry no data. That is why the acknowledgment of a SYN with sequence number x is x + 1. The initial sequence number is chosen unpredictably, not as 0. A predictable value would make it easier for an attacker to forge segments.
Data offset
The data offset says where the header ends and the payload begins. It counts 32-bit words, so the header length in bytes is the offset times 4. The smallest legal value is 5 (20 bytes). The largest is 15 (60 bytes), which leaves room for at most 40 bytes of options.
Window
The window field advertises how many bytes the sender of the segment is willing to receive beyond the acknowledged position. This is the basis of flow control, covered in its own chapter. The field is 16 bits, so it tops out at 65,535 bytes unless the window scale option is in use.
The flags
Each flag is one bit.
| Flag | Meaning |
|---|---|
| SYN | Synchronize sequence numbers. Opens a connection. |
| ACK | The acknowledgment number field is valid. Set on nearly every segment after the first SYN. |
| FIN | The sender has no more data. Starts closing its direction. |
| RST | Reset. Abort the connection immediately, for example when a segment arrives for a port nobody is listening on. |
| PSH | Push. Hints that the receiver should deliver buffered data to the application now. |
| URG | The urgent pointer is valid. Rarely used today. |
| ECE, CWR | Signal explicit congestion notification between the endpoints. |
Options
If the data offset is greater than 5, the bytes between the fixed header and the payload are options. Each option has a one-byte kind. Most also have a one-byte length and a body. Two kinds are special. Kind 0 marks the end of the list, and kind 1 is a one-byte no-operation used for padding so that options stay aligned to 32-bit words.
| Kind | Name | Used for |
|---|---|---|
| 2 | Maximum segment size | Announces the largest payload the sender will accept. SYN segments only. |
| 3 | Window scale | A shift count that multiplies the window field. SYN segments only. |
| 4 | SACK permitted | Offers selective acknowledgment. SYN segments only. |
| 5 | SACK | Reports ranges of bytes received out of order. |
| 8 | Timestamps | Round-trip time measurement and protection against old duplicate segments. |
The window scale option works as follows. A shift of 7 multiplies the advertised window by 128, so the 16-bit field can describe windows of several megabytes. The maximum shift is 14, giving a window of about 1 GiB. Without scaling, a 65,535-byte window limits throughput on long, fast paths. A link with a 100 ms round trip would be capped near 5 Mbit/s, however fast the link is.
Reading a header in code
The program below builds a realistic SYN header with options, then parses it. It uses only the standard library. The format string !HHIIHHHH means network byte order, four 16-bit fields, two 32-bit fields, then four more 16-bit fields. Those are the fixed 20 bytes.
import struct
FLAGS = [("CWR", 0x80), ("ECE", 0x40), ("URG", 0x20), ("ACK", 0x10),
("PSH", 0x08), ("RST", 0x04), ("SYN", 0x02), ("FIN", 0x01)]
def parse_options(opts):
found = []
i = 0
while i < len(opts):
kind = opts[i]
if kind == 0: # end of option list
break
if kind == 1: # no-operation padding
found.append("NOP")
i += 1
continue
length = opts[i + 1]
if length < 2: # malformed, avoid looping forever
break
body = opts[i + 2:i + length]
if kind == 2:
found.append(f"MSS={struct.unpack('!H', body)[0]}")
elif kind == 3:
found.append(f"WScale={body[0]}")
elif kind == 4:
found.append("SACK-permitted")
elif kind == 8:
tsval, tsecr = struct.unpack("!II", body)
found.append(f"Timestamps({tsval},{tsecr})")
else:
found.append(f"kind{kind}")
i += length
return found
def parse_tcp_header(data):
src, dst, seq, ack, off_flags, window, checksum, urg = \
struct.unpack("!HHIIHHHH", data[:20])
header_len = (off_flags >> 12) * 4
flags = [name for name, bit in FLAGS if off_flags & bit]
return {
"src_port": src,
"dst_port": dst,
"seq": seq,
"ack": ack,
"header_len": header_len,
"flags": flags,
"window": window,
"checksum": checksum,
"urgent": urg,
"options": parse_options(data[20:header_len]),
}
options = (
bytes([2, 4]) + struct.pack("!H", 1460) # MSS 1460
+ bytes([4, 2]) # SACK permitted
+ bytes([8, 10]) + struct.pack("!II", 1, 0) # timestamps
+ bytes([1]) # NOP padding
+ bytes([3, 3, 7]) # window scale 7
)
offset_words = (20 + len(options)) // 4 # 40 bytes -> 10 words
header = struct.pack("!HHIIHHHH", 51514, 443, 3000000000, 0,
(offset_words << 12) | 0x02, # data offset + SYN flag
65535, 0, 0) + options
for key, value in parse_tcp_header(header).items():
print(f"{key:11} {value}")The output shows a 40-byte header, only the SYN flag set, an acknowledgment number of 0 (ignored because ACK is clear), and the four options. The checksum is 0 here because we built the header by hand. A real checksum covers a pseudo-header made from the IP addresses, so it cannot be computed from the TCP bytes alone.
Common errors and gotchas
- Treating the header as 20 bytes. The payload starts at
data offset * 4. Code that hard-codes 20 breaks on any segment with options, which includes nearly all segments sent with timestamps. - Confusing segments with
send()calls. Onesendall()can become several segments, and several calls can be merged into one. Your application's write boundaries are not in the header. The next chapters cover this. - Forgetting the phantom byte. SYN and FIN each use one sequence number. Off-by-one errors in packet analysis scripts usually come from this.
- Expecting the full MSS everywhere. The MSS option only states what each end can accept. Path MTU limits and tunnels (VPNs add their own headers) can force smaller segments. A path that silently drops large packets can leave a connection stalling after the handshake succeeds.
- Reading the acknowledgment number when ACK is clear. The field is meaningless in that case and is often zero.
Exercise
A segment arrives with sequence number 7200, data offset 8, and a total TCP length (header plus payload) of 532 bytes. How long is the header, how many payload bytes are there, and what acknowledgment number should the receiver send back if it accepts the segment and has received all earlier bytes?
Show answer
The header is 8 x 4 = 32 bytes, so 12 of those bytes are options. The payload is 532 - 32 = 500 bytes, covering sequence numbers 7200 to 7699. The receiver acknowledges with 7200 + 500 = 7700, the next byte it expects.
Exercise
Why does a server's SYN-ACK to a client SYN with sequence number 4000 carry an acknowledgment number of 4001, even though the SYN carried no data?
Show answer
The SYN flag consumes one sequence number. The acknowledgment number names the next sequence number the receiver expects, so it is 4000 + 1 = 4001.