AlgoPlusAlgoPlus
Learn/Networking
Lesson

TCP Three-Way Handshake

Before any data moves, both sides exchange and acknowledge starting sequence numbers: SYN, SYN-ACK, ACK.

8 min read Watch it move Build it

TCP promises a *reliable, ordered byte stream* — but it runs over IP, which loses, reorders, and duplicates packets freely. To deliver on that promise, both sides must first agree on where the stream *starts*. That agreement is the three-way handshake: SYN, SYN-ACK, ACK. It costs exactly one round trip before the first byte of real data can flow.

Sequence numbers — the thing being agreed

TCP labels every byte with a sequence number so the receiver can reorder what arrives and detect what's missing. Each side picks its *own* starting sequence number (an ISN, chosen unpredictably for safety). The handshake exists so each side learns the other's starting number and confirms it was heard.

The three packets

  1. 1SYN — the client sends a packet with the SYN flag set and its starting sequence number, say x. (Client: SYN-SENT.)
  2. 2SYN-ACK — the server replies with SYN carrying *its* starting number y, plus an ACK of x+1 (the next byte it expects from the client). One packet does both jobs. (Server: SYN-RECEIVED.)
  3. 3ACK — the client acknowledges the server's number with ACK y+1. The connection is now ESTABLISHED and data can flow.
Why three and not two
Each direction's sequence number must be both sent and acknowledged. The middle packet (SYN-ACK) cleverly merges the server's SYN with its ACK of the client, so what would be four messages collapses into three.
Client                         Server
  |  --- SYN  seq=x ----------->  |
  |  <-- SYN-ACK seq=y ack=x+1 -  |
  |  --- ACK  ack=y+1 -------->   |
  |        (ESTABLISHED)          |
Opening is three, closing is four
Tearing a connection down is *not* symmetric with opening. Each side closes its own direction with a FIN that the other ACKs — a four-way exchange — because one side may keep sending after the other is done.
OperationTimeSpace
Establish · SYN, SYN-ACK, ACK1 RTT
Close · four-way FIN exchange~2 RTT
Check yourself
What does the server's SYN-ACK packet accomplish in a single message?