Networking / TCP three-way handshake
TCP three-way handshake
Before two machines trade a single byte, they swap three small packets to agree on how to count. Here is every packet, every state, and why three is the magic number.
Client — opens the connection
Server — listens and answers
Packet — carries flags plus seq and ack numbers
// THE SHORT VERSION
In 30 seconds
Before sending any data, two machines using TCP exchange three small packets: SYN, SYN-ACK, ACK.
Each side picks a starting sequence number and tells the other; each confirms it heard by replying with that number plus one.
After the third packet both know the other can send and receive, and both know where counting starts, so lost or reordered bytes can be spotted later.
TCP three-way handshake, step by step
STEPS01 / 07
Real ISNs are random 32-bit numbers. We use 1000 and 5000 so the arithmetic stays readable.
STEP 01 / 07
Two machines, no link
THE MATH
client: CLOSED
server: LISTEN (port 80)
- Step 1: Two machines, no link. The server has opened a socket and is waiting. The client wants to talk, but neither side yet knows where the other will start numbering its bytes.
- Step 2: SYN. The client picks its initial sequence number, 1000, and sends a SYN (“synchronise”). It says: let’s talk, and I’ll count my bytes from here.
- Step 3: SYN-ACK. The server answers with its own SYN and number, 5000, and acknowledges the client’s: ack = 1001 means “I got 1000, I expect 1001 next.”
- Step 4: ACK. The client acknowledges the server’s number. Now both sides have proven they can send and receive, and both know both starting numbers.
- Step 5: Why three, not two?. A delayed SYN from an old attempt can reach the server. With two messages the server would open a connection for a ghost. The third message lets the client say “that isn’t me.”
- Step 6: Sending data. Sequence numbers count bytes. Each acknowledgement names the next byte expected, so a missing ack tells the sender exactly what to resend.
- Step 7: Saying goodbye. Each direction closes on its own: a FIN and its ACK, twice. The client lingers in TIME_WAIT in case its last ACK is lost and the server’s FIN comes again.
VALUES SO FAR
x····client ISN
y····server ISN
ack····x + 1
ack····y + 1
state····both
ghost····rejected
C→S····acked
S→C····acked
close····4-way
// PLAYGROUND
Try it yourself
// YOUR PROGRESS
// BEFORE
Learn this first
Nothing. This concept starts from scratch.
Spotted a mistake on this page?