TCP Segments
TCP (Transmission Control Protocol, RFC 9293) turns IP's unreliable packets into a reliable, ordered, two-way byte stream between two programs. The web, email, SSH and databases all depend on it. TCP takes care of:
- connections: a handshake to start, an orderly close at the end,
- reliability: every byte is acknowledged; missing bytes are resent,
- ordering: out-of-order segments are put back in sequence,
- flow control: never sending more than the receiver can buffer,
- congestion control: slowing down when the network is overloaded.
This lesson looks at the TCP header; the next three cover connections, reliability and congestion control.
The header
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-------------------------------+-------------------------------+
| Source Port | Destination Port |
+-------------------------------+-------------------------------+
| Sequence Number |
+---------------------------------------------------------------+
| Acknowledgment Number |
+-------+-------+---------------+-------------------------------+
| Offset| Rsrvd | Flags | Window |
+-------+-------+---------------+-------------------------------+
| Checksum | Urgent Pointer |
+-------------------------------+-------------------------------+
| Options (0-40 bytes) || Field | Meaning |
|---|---|
| Sequence number | position in the byte stream of this segment's first data byte |
| Acknowledgment number | the next byte the sender expects to receive (valid when ACK is set) |
| Data offset | header length in 32-bit words (5 = 20 bytes) |
| Flags | CWR, ECE, URG, ACK, PSH, RST, SYN, FIN |
| Window | how many bytes the sender of this segment is willing to receive |
| Checksum | Internet checksum over a pseudo-header + header + data (like UDP) |
| Options | MSS, window scale, SACK permitted, timestamps |
Flags
| Flag | Bit | Meaning |
|---|---|---|
| FIN | 0x01 | I have finished sending |
| SYN | 0x02 | synchronise sequence numbers (start a connection) |
| RST | 0x04 | reset: abort the connection immediately |
| PSH | 0x08 | push buffered data to the application now |
| ACK | 0x10 | the acknowledgment number is valid |
| URG | 0x20 | urgent pointer is valid (rarely used) |
FLAG_NAMES = ["FIN", "SYN", "RST", "PSH", "ACK", "URG", "ECE", "CWR"]
def decode_flags(value):
return "|".join(name for bit, name in enumerate(FLAG_NAMES) if value & (1 << bit)) or "none"
for value in [0x02, 0x12, 0x10, 0x18, 0x11, 0x04, 0x29]:
print(f"0x{value:02x} = {value:08b} -> {decode_flags(value)}")0x02 = 00000010 -> SYN
0x12 = 00010010 -> SYN|ACK
0x10 = 00010000 -> ACK
0x18 = 00011000 -> PSH|ACK
0x11 = 00010001 -> FIN|ACK
0x04 = 00000100 -> RST
0x29 = 00101001 -> FIN|PSH|URG
The last one (FIN|URG|PSH) is the famous "Christmas tree" packet, lit up like a tree. It never occurs in normal traffic; port scanners use it to probe how a host reacts.
Building and parsing a SYN segment
import socket
import struct
def checksum(data):
if len(data) % 2:
data += b"\0"
total = sum(struct.unpack(f"!{len(data) // 2}H", data))
while total >> 16:
total = (total & 0xFFFF) + (total >> 16)
return ~total & 0xFFFF
def tcp_segment(src_ip, dst_ip, sport, dport, seq, ack, flags, window, options=b"", payload=b""):
offset_words = (20 + len(options)) // 4
header = struct.pack("!HHIIBBHHH", sport, dport, seq, ack, offset_words << 4, flags, window, 0, 0)
header += options
pseudo = struct.pack("!4s4sBBH", socket.inet_aton(src_ip), socket.inet_aton(dst_ip),
0, socket.IPPROTO_TCP, len(header) + len(payload))
csum = checksum(pseudo + header + payload)
return header[:16] + struct.pack("!H", csum) + header[18:] + payload
mss_option = struct.pack("!BBH", 2, 4, 1460) # kind 2 = MSS, length 4
nop_wscale = bytes([1, 3, 3, 7]) # NOP, window scale (kind 3, len 3, shift 7)
syn = tcp_segment("192.168.1.20", "93.184.215.14", 51514, 443,
seq=2_000_000_000, ack=0, flags=0x02, window=64240,
options=mss_option + nop_wscale)
print(len(syn), "bytes:", syn.hex(" "))
sport, dport, seq, ack, off, flags, window, csum, urg = struct.unpack("!HHIIBBHHH", syn[:20])
print(f"{sport} -> {dport} seq={seq} ack={ack} header={(off >> 4) * 4}B flags=0x{flags:02x} win={window}")
print("options:", syn[20:].hex(" "))28 bytes: c9 3a 01 bb 77 35 94 00 00 00 00 00 70 02 fa f0 bc 78 00 00 02 04 05 b4 01 03 03 07
51514 -> 443 seq=2000000000 ack=0 header=28B flags=0x02 win=64240
options: 02 04 05 b4 01 03 03 07
The SYN advertises a maximum segment size of 1460 (Ethernet MTU 1500 − 40) and a window scale of 7, which multiplies the 16-bit window field by 2^7 = 128 for the rest of the connection. Without scaling, a window could never exceed 65,535 bytes, too small for fast long-distance links.
Sequence numbers count bytes
TCP numbers bytes, not segments. If a segment with sequence number 1000 carries 500 bytes, the next one starts at 1500, and the receiver acknowledges with ACK 1500 ("I have everything before byte 1500, send 1500 next"). SYN and FIN each consume one sequence number even though they carry no data.
isn = 2_000_000_000 # initial sequence number chosen by the client
data = b"x" * 3500
mss = 1460
seq = isn + 1 # the SYN used up one number
offset = 0
while offset < len(data):
chunk = data[offset:offset + mss]
print(f"segment seq={seq} len={len(chunk):>4} -> receiver replies ACK {seq + len(chunk)}")
seq += len(chunk)
offset += len(chunk)
print("relative numbers (as Wireshark shows):", [s - isn for s in (isn + 1, isn + 1461, isn + 2921)])
print("wraps around after", 2 ** 32, "bytes:", (2 ** 32 - 10 + 25) % 2 ** 32)segment seq=2000000001 len=1460 -> receiver replies ACK 2000001461
segment seq=2000001461 len=1460 -> receiver replies ACK 2000002921
segment seq=2000002921 len= 580 -> receiver replies ACK 2000003501
relative numbers (as Wireshark shows): [1, 1461, 2921]
wraps around after 4294967296 bytes: 15
Initial sequence numbers are chosen unpredictably (RFC 6528) so attackers can't guess them and inject fake segments into a connection. Wireshark shows relative sequence numbers (starting from 0) to make captures readable.
Seeing TCP on the wire
sudo tcpdump -n -i eth0 'tcp port 443' -c 3Sample output:
10:15:02.118230 IP 192.168.1.20.51514 > 93.184.215.14.443: Flags [S], seq 2000000000, win 64240, options [mss 1460,sackOK,TS val 1855012 ecr 0,nop,wscale 7], length 0
10:15:02.130011 IP 93.184.215.14.443 > 192.168.1.20.51514: Flags [S.], seq 3141592653, ack 2000000001, win 65535, options [mss 1400,sackOK,TS val 99102 ecr 1855012,nop,wscale 9], length 0
10:15:02.130104 IP 192.168.1.20.51514 > 93.184.215.14.443: Flags [.], ack 1, win 502, length 0In tcpdump's notation, S is SYN, . is ACK, P is PSH, F is FIN and R is RST. That capture is a complete 3-way handshake, the topic of the next lesson.
Test yourself
A segment has sequence number 5000 and carries 1200 bytes. What ACK number does the receiver send back?
- 5000
- 5001
- 6200
- 6201
Which flags are set in the second packet of the handshake?
- SYN only
- SYN and ACK
- ACK only
- FIN and ACK
What does the RST flag mean?
- Resend the last segment
- Restart the handshake politely
- Abort the connection immediately
- Reset the window size