Walk me through the TCP three-way handshake.
Short answer
TCP opens a connection in three steps. The client sends a SYN with an initial sequence number, the server replies with SYN-ACK (acknowledging the client's number and sending its own), and the client returns an ACK. After this exchange both sides have agreed on starting sequence numbers and the connection is established for reliable, ordered byte delivery.
The three-way handshake exists because TCP promises something UDP does not: reliable, ordered delivery of a byte stream. To keep that promise, both ends must agree on where the stream starts before any application data moves. That agreement is the handshake.
The three steps
- SYN. The client picks a random initial sequence number (ISN) and sends a segment with the SYN flag set, advertising that ISN. This is the client saying "I want to talk, and my bytes will be numbered starting here."
- SYN-ACK. The server replies with its own SYN (its own ISN) and an ACK that acknowledges the client's ISN + 1. In one segment the server both accepts the connection and announces its own numbering.
- ACK. The client acknowledges the server's ISN + 1. Now both sides know each other's starting sequence number, and the connection moves to the ESTABLISHED state.
Why sequence numbers matter
Sequence numbers let TCP detect loss, reorder out-of-order segments, and discard duplicates. Randomizing the ISN also makes it much harder for an off-path attacker to spoof or inject segments into the stream, since they would have to guess the numbers.
The security angle
The handshake is also an attack surface. A SYN flood sends many SYNs and never completes the third step, exhausting the server's table of half-open connections. SYN cookies defend against this by encoding connection state into the server's ISN so no memory is reserved until the final ACK arrives.
Interviewers want to hear the three packet names in order, that sequence numbers are being synchronized (not data being sent), and ideally a nod to SYN floods.
Likely follow-ups
- What is a SYN flood and how does a SYN cookie defend against it?
- How does TCP tear a connection down, and what is the role of TIME_WAIT?
- Why does TCP randomize the initial sequence number?