TCP Three-Way Handshake Mechanism
TCP Handshake Process
The TCP three-way handshake consists of the following steps:
- SYN: The client sends a SYN (synchronize) packet with a randomly generated initial sequence number (ISN).
- SYN-ACK: The server responds with a SYN-ACK packet. This acknowledges the client's SYN (ACK = client ISN + 1) and sends its own ISN.
- ACK: The client sends an ACK packet to acknowledge the server's SYN (ACK = server ISN + 1).
At this point, the connection is established and data transfer can begin.
Consolidation from Logical Four-Way to Practical Three-Way Handshake
Theoretically, establishing a reliable connection with synchronized sequence numbers requires four message exchanges: Cliant SYN, Server ACK for Client SYN, Server SYN, and Client ACK for Server SYN.
Since the Server's ACK and its own SYN can be combined in to a single SYN-ACK packet without any intervening events, these two logical steps are merged. This reduces the handshake to three packets, optimizing connection setup latency and reducing network overhead.
Purpose of the Handshake
The handshake is required to initialize and synchronize the state information necessary for TCP's reliable, ordered data stream service.
A TCP connection is defined by the combined status information on both ends, including socket pairs, sequence numbers, and window sizes for flow control. The handshake ensures both peers agree on these initial parameters before data transmission commences.
Preventing Connection Confusion from Delayed Packets
A primary rationale for the three-way exchange is to prevent old or duplicate connection initiation segments from causing issues. Consider a scenario with only a two-way handshake:
- A delayed SYN packet from a previous, closed connection arrives at the server.
- The server, believing it's a new request, acknowledges it and considers the connection open.
- The client, having no context for this acknowledgment, ignores it, leaving the server with a "half-open" connection that consumes resources.
The three-way handshake mitigates this. The client must explicitly acknowledge the server's SYN. If the client does not have an active request, it will not send this final ACK, preventing the server from fully establishing a connection based on a stale request.
Synchronizing Sequence Numbers
Sequence numbers are fundamental to TCP's reliability, enabling duplicate detection, ordered delivery, and acknowledgment of received data. The Initial Sequence Number (ISN) is randomized for security. The handshake allows both sides to exchange and acknowledge each other's ISN.
- The client's SYN communicates its ISN to the server.
- The server's SYN-ACK acknowledges the client's ISN and communicates its own ISN.
- The client's final ACK acknowledges the server's ISN. This mutual exchange and acknowledgment insure both sides have a synchronized starting point for tracking data segments.