TCP Handshake
SYN, SYN-ACK, ACK. Sequence numbers exchanged so a connection can start.
Level: beginner
What is it?
TCP is connection-oriented. Before either side sends application data, they run a three-way handshake so both agree that a connection exists and both know the other's starting sequence number.
Why does it matter?
Almost every HTTP/1.1 and TLS session on TCP begins here. Connection latency (one RTT before data, plus more for TLS) is this handshake. SYN floods are this handshake abused.
Mental model
Two people picking a numbering system before they talk. 'I will start at 42' / 'I heard 42, I will start at 99' / 'I heard 99.' After that, every byte has a number and losses can be named.
How it works
- Client sends SYN with its initial sequence number (ISN) and options (window scale, SACK, MSS).
- Server replies SYN-ACK with its own ISN and acknowledges client ISN+1. The TCB (transmission control block) is created, or a SYN cookie is used.
- Client sends ACK of server ISN+1. The connection is ESTABLISHED on both sides (server already was after the ACK arrives).
- Data can be piggybacked on that third ACK, but browsers usually wait (and then do TLS).
- Each SYN consumes state. Unanswered SYNs are how SYN floods fill a backlog.
Steps
- Client: flags=SYN, seq=x, options=MSS, WS, SACK-permitted, TSval.
- Server: flags=SYN+ACK, seq=y, ack=x+1.
- Client: flags=ACK, seq=x+1, ack=y+1.
- Both state machines sit in ESTABLISHED. Application write() now produces segments with payload.
Code example: A capture in words
C → S SYN seq=1000 win=65535 mss=1460
S → C SYN-ACK seq=5000 ack=1001
C → S ACK seq=1001 ack=5001
C → S PSH-ACK seq=1001 ack=5001 "GET / HTTP/1.1..."Real-world usage
- Every TCP connect()
- Load balancer health and connection tracking
- Diagnosing 'connection timed out' vs 'connection reset'
Common mistakes
- Calling it a 'three-way handshake of HTTP'. HTTP may reuse a connection; the handshake is TCP's.
- Forgetting that sequence numbers count bytes, not segments.
- Assuming the server is ESTABLISHED after SYN-ACK. It is SYN-RECEIVED until the ACK arrives (unless you are hand-waving).
Interview questions
Draw the three-way handshake with sequence numbers.
SYN seq=x; SYN-ACK seq=y ack=x+1; ACK seq=x+1 ack=y+1.
Why three ways, not two?
Both sides must advertise an ISN and learn the other. Two ways would leave one side unsure the peer received its ISN.
What is a SYN cookie?
A server that encodes the SYN state into the ISN so it does not store a TCB until the ACK arrives — a SYN-flood defense.