sockets · advanced
Sockets: TCP Handshake, Teardown & TIME_WAIT
TCP establishes a connection with a three-way handshake: the client sends SYN with an initial sequence number x, the server replies SYN+ACK (its own sequence y, acknowledging x+1), and the client sends ACK (acknowledging y+1), after which both sides have synchronized sequence numbers in each direction and the connection is ESTABLISHED — three packets being the minimum needed to synchronize both ways (connect() returns on the client, accept() on the server). Because TCP is full-duplex, teardown is independent per direction and takes four segments: the side calling close() sends FIN, the peer ACKs it (closing that half while still able to send), then the peer sends its own FIN which is ACKed; shutdown(fd, SHUT_WR) can send a FIN while continuing to read, a legal half-close. The side that closes actively (sends the last ACK) then enters TIME_WAIT for 2*MSL (roughly 30-120 seconds) so that delayed or duplicate packets expire and the peer's final FIN can be re-acknowledged. This is why immediately restarting a server often fails to bind with EADDRINUSE ('Address already in use') — its port is still in TIME_WAIT — and the fix is to set SO_REUSEADDR before bind(); a large number of TIME_WAIT sockets generally indicates that this side actively closes many short-lived connections.
TCP setup is a 3-way handshake (SYN, SYN+ACK, ACK) syncing sequence numbers; teardown is 4-way (FIN/ACK per direction, half-close via shutdown). The active closer enters TIME_WAIT (2*MSL), causing EADDRINUSE on restart — fix with SO_REUSEADDR before bind().
The code
// 3-way handshake (connection setup)client --- SYN(seq=x) ------------> server // I want to talkclient <-- SYN(seq=y) ACK(x+1) ---- server // ok, and you?client --- ACK(y+1) -------------> server // established
// 4-way teardown (each side closes its half independently)FIN -> ; <- ACK ; <- FIN ; ACK -> // then TIME_WAITWhat this lesson walks through
- 01The 3-way handshake — CLOSED → ESTABLISHED
- 024-way teardown — each half closes independently
- 03TIME_WAIT — the active closer waits 2·MSL
- 04Gotcha — port exhaustion & SO_REUSEADDR
Connection setup takes three packets. The client sends SYN (seq x); the server replies SYN+ACK; the client ACKs. Three messages and both sides agree on sequence numbers — now ESTABLISHED.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Sockets: TCP Handshake, Teardown & TIME_WAIT and 100+ animated C++ interview lessons.