6.4 TCP Connection Management: 3-Way Handshake & 4-Way Teardown
💡 Core Intuition: The Diplomatic Bilateral Agreement
🍳 The Everyday Analogy: Negotiating and Terminating a Formal Contract
Imagine two corporate ambassadors, Alice (Client) and Bob (Server), drafting an exclusive business contract:
- Step 1 (Alice proposes): Alice mails a signed proposal stating:
- Step 2 (Bob confirms & proposes back): Bob signs Alice's proposal and attaches his own ledger terms:
- Step 3 (Alice acknowledges Bob): Alice writes back:
Now, when business concludes, either party can close their side of the warehouse independently:
- Alice says, "I have shipped all my goods; my warehouse is closed to further dispatches" ().
- Bob acknowledges, "Understood; I will sign your exit receipt" ().
- Bob can continue shipping his remaining inventory until he is done, after which Bob sends his own , and Alice sends the final .
💻 Bridging to Computer Science: Synchronized Connection State Machines
In computer networking, two independent endpoints communicating across an unreliable network cannot presuppose that the peer is alive, listening, and ready to receive. Before data streaming can begin, both endpoints must:
- Confirm bidirectional communication reachability (Host A can reach Host B, and Host B can reach Host A).
- Establish synchronized starting sequence numbers () so data bytes can be tracked without ambiguity.
- Exchange flow control window buffers () and maximum segment sizes ().
Similarly, when tearing down the connection, each simplex direction must be closed independently without data loss. This bilateral lifecycle is achieved through the TCP 3-Way Handshake and 4-Way Teardown.
🤝 TCP Connection Establishment: The 3-Way Handshake
TCP creates a virtual full-duplex circuit between endpoints through a synchronized three-step message exchange.
TCP 3-Way Handshake Sequence & State Transitions
Interactive sequence diagram tracing Initial Sequence Number (ISN) negotiation and control flags
Frame transmitted across physical communication link.
Step-by-Step Handshake Protocol Analysis
Step 1: Active Open (Client Server)
- Control Flags: .
- Fields: (Client Initial Sequence Number, ISN). The Acknowledgment field contains no valid data.
- State Transition: The client transitions from
CLOSEDtoSYN_SENT. - Sequence Consumption: Although the SYN segment carries bytes of application data, it consumes exactly sequence number because it requires explicit acknowledgment.
Step 2: Passive Open Response (Server Client)
- Control Flags: .
- Fields: (Server ISN), and (confirming receipt of client's byte ).
- State Transition: The server transitions from
LISTENtoSYN_RCVD. - Sequence Consumption: Like the client SYN, the server SYN+ACK carries bytes of application data but consumes exactly sequence number.
Step 3: Connection Confirmation (Client Server)
- Control Flags: .
- Fields: , and (confirming receipt of server's byte ).
- State Transitions:
- The client transitions to
ESTABLISHEDimmediately upon sending this segment. - The server transitions from
SYN_RCVDtoESTABLISHEDupon receiving this segment.
- The client transitions to
- Sequence Consumption: A pure ACK carries data bytes and consumes sequence numbers! (If the client attaches piggybacked data in this third packet, the sequence numbers advance by the length of that data).
❓ Why isn't a 2-Way Handshake Sufficient?
A classic question asked across academia and industry: Why does TCP mandate three messages instead of just two?
Why 2-Way Handshake Fails: The Delayed Duplicate SYN Hazard
How the 3rd handshake step empowers the client to abort phantom connections via RST
Frame transmitted across physical communication link.
- The Delayed Duplicate SYN Hazard: Suppose a client transmits a SYN packet that gets stuck in an overloaded internet router queue for minutes. The client times out, opens another connection, completes data transfer, and terminates.
- Later, the old delayed SYN finally arrives at the server.
- If only a 2-Way Handshake existed:
- The server would receive the old SYN, allocate socket memory buffers, and reply with an ACK.
- The server would immediately consider the connection
ESTABLISHEDand sit idle forever waiting for data! - The client, having already finished its session, would ignore the server's ACK.
- With a 3-Way Handshake:
- The server sends a
SYN+ACKexpecting the client's 3rd ACK. - The client receives an unexpected
SYN+ACKfor an old sequence number . - The client detects the anomaly and transmits an active
RST(Reset) segment, forcing the server to safely abort and release its allocated memory!
- The server sends a
✂️ TCP Connection Termination: The 4-Way Teardown
Because TCP is a full-duplex protocol, each direction of data transit operates independently. Closing a TCP connection requires gracefully shutting down both unidirectional channels.
TCP 4-Way Connection Teardown & Half-Close Mechanics
Interactive sequence tracing graceful independent termination in each direction
Frame transmitted across physical communication link.
The Half-Close Connection State (SHUT_WR)
- When the client sends
FINand the server replies withACK, the connection enters the Half-Close state. - The client cannot transmit any further application bytes.
- However, the server can still transmit data to the client! The client continues to accept and acknowledge the server's data until the server finally transmits its own
FINsegment. - In C socket programming, an application creates a half-close by executing:
shutdown(sockfd, SHUT_WR); // Closes outbound write channel, leaves inbound read channel open
🏭 Real-World Production Context: Mitigating SYN Flood Attacks with Linux SYN Cookies
The 3-way handshake exposes a classic vulnerability known as the SYN Flood Attack.
SYN Flood Denial-of-Service Attack Cascade
How spoofed SYN packets deplete server kernel memory and block legitimate users
Spoofed SYN Avalanche
Attacker floods victim with thousands of SYN packets containing unreachable forged source IPs.
Kernel Backlog Saturation
Server allocates TCB state memory and SYN-ACK timers for phantom clients that never respond.
Legitimate Clients Blocked
Authentic client connection requests are dropped because the server's SYN queue has no free slots.
The Attack Mechanism:
- An attacker transmits an overwhelming deluge of TCP
SYNpackets with randomized, spoofed source IP addresses. - For each incoming
SYN, the server allocates a Transmission Control Block (TCB) in kernel memory, allocates send/receive buffers, initializes timers, and returns aSYN+ACKto the spoofed IP. - Because the spoofed IPs do not exist or ignore the unsolicited
SYN+ACK, the 3rdACKpacket never arrives. - The server's Half-Open Connection Queue (SYN Backlog) completely fills up. When legitimate clients attempt to connect, the server drops their SYN packets, resulting in a Denial of Service (DoS).
The Architectural Solution: SYN Cookies (RFC 4987)
To neutralize SYN flood attacks without consuming server memory, modern operating systems implement SYN Cookies:
- When the server receives a
SYN, it allocates ZERO memory and creates NO kernel state block (TCB)! - Instead, the server encodes all connection parameters inside its choice of Initial Sequence Number ():
- The server transmits
SYN+ACKwith . If the client was spoofed, nothing happens, and zero server memory is consumed. - If the client is legitimate, it returns the 3rd
ACKwith . - The server subtracts from the incoming acknowledgment number (), re-computes the hash, and verifies that the cookie matches!
- Only upon successful cryptographic validation does the server finally allocate kernel memory for the TCB and transition to
ESTABLISHED.
📐 Numerical Applications & Worked Examples
Example 1: Handshake Flag and Sequence Number Negotiation
Problem Statement:
Consider the three-way handshake mechanism followed during TCP connection establishment between Host (Client) and Host (Server). Let and be 32-bit Initial Sequence Numbers (ISNs) selected by and respectively. Suppose initiates a connection request by transmitting a TCP segment with , , and . If accepts the connection request, determine the exact control flags, sequence number, acknowledgment number, and payload consumption in the segment returned by to .
Step-by-Step Solution:
- Analyze Server Synchronization Requirements:
Host must accomplish two distinct protocol requirements in its response:- Synchronize its local sequence space: asserts and announces its own initial sequence number: .
- Acknowledge the client's request: asserts to validate receipt of 's initial segment.
- Determine Acknowledgment Number:
Even though the initial connection request carries zero application payload bytes, RFC 793 dictates that a control segment consumes exactly sequence number (). Therefore, expects byte next: - Evaluate Remaining Flags:
Because this segment belongs to the connection establishment phase, the flag remains cleared (). - Resulting Segment Parameters:
Example 2: Handshake Packet Loss and State Progression
Problem Statement:
Evaluate the robustness of the TCP connection establishment protocol under packet loss and determine the validity of the following three architectural assertions:
- Loss of the server's segment in transit prevents connection establishment on that attempt.
- Loss of the client's final segment in transit permanently prevents connection establishment.
- During a standard passive open without loss, the server transitions through .
Step-by-Step Solution:
- Evaluate Assertion 1 (Loss of Server ):
If the server's is dropped in the network, the client never learns the server's ISN () and never dispatches the third ACK. The client remains stuck inSYN_SENTuntil its retransmission timer expires to retry. For that exchange attempt, no connection is established. Assertion 1 is Valid. - Evaluate Assertion 2 (Loss of Final Client ):
Upon transmitting the final , the client immediately transitions toESTABLISHEDand can immediately send application data. Any subsequent data segment carries the flag set, which satisfies the server. Furthermore, the server's retransmission timer inSYN_RCVDwill re-send , prompting the client to retransmit the ACK. Thus, establishment is not permanently precluded. Assertion 2 is Invalid. - Evaluate Assertion 3 (Server State Sequence):
In a normal passive open:- Server begins in
LISTEN. - Receiving a client
SYNcauses the server to sendSYN+ACKand enterSYN_RCVD. - Receiving the client's
ACKcompletes the handshake and moves the server toESTABLISHED. - Note that
SYN_SENTis strictly an active-open client state and is never traversed by the server during passive open. Assertion 3 is Valid.
- Server begins in
Example 3: Half-Close Connection Data Flow and Sequence Numbers
Problem Statement:
Host and Host operate an established TCP connection. Host initiates a half-close by transmitting a FIN segment with sequence number and acknowledgment number . Host receives this segment and acknowledges it. Subsequently, Host transmits bytes of application data to Host . Determine the exact sequence and acknowledgment numbers used across all three exchanges.
Step-by-Step Solution:
- Host 's Acknowledgment of Host 's
FIN:
Host 'sFINconsumes sequence number (). Host acknowledges this segment with: Host entersFIN_WAIT_2, and Host entersCLOSE_WAIT. - Host 's 800-Byte Data Segment:
Because Host has not closed its outbound channel, it transmits its data starting at its current sequence number: The sequence numbers consumed by this data span . - Host 's Acknowledgment of Data:
Host receives the bytes and acknowledges the next expected byte: Host remains inFIN_WAIT_2until Host concludes its transfer and sends its ownFIN.
🎯 Exam & Interview Pitfall Check
- How many sequence numbers does a SYN segment consume?
Exactly sequence number, despite containing bytes of application data. This is necessary because any segment that changes state must be reliably acknowledged. - How many sequence numbers does a pure ACK segment consume?
Exactly sequence numbers. An ACK that carries no data and no SYN/FIN flags does not advance the sequence number space and is never acknowledged by the peer (preventing infinite acknowledgment loops).
- Trap: Believing that a lost ACK causes the connection to instantly drop.
Debunked: If the client's 3rd ACK is lost, the server's retransmission timer fires and retransmits theSYN+ACK. When the client receives the duplicateSYN+ACK, it simply re-sends the ACK. - Trap: Assuming both sides close simultaneously in everyday traffic.
Debunked: While simultaneous close is handled by the TCP specification, standard web traffic follows an asymmetrical teardown: one endpoint (often the client or web server) issues an active close (FIN), and the other responds passively before initiating its own close.