Skip to main content

6.4 TCP Connection Management: 3-Way Handshake & 4-Way Teardown

📚Module 06: Transport Layer: UDP, TCP & Connection FlowTopic 6.4⏱️24 min read
🎯High-Yield For:Semester Exams (All Universities) • Placement Technical Rounds • Engineering Foundations

💡 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: "I wish to open business with you. My initial document serial is 1000. Do you agree?"(SYN)\text{"I wish to open business with you. My initial document serial is 1000. Do you agree?"} \quad (\mathbf{SYN})
  • Step 2 (Bob confirms & proposes back): Bob signs Alice's proposal and attaches his own ledger terms: "I accept your document 1000 (send 1001 next). My initial document serial is 5000. Do you agree?"(SYN+ACK)\text{"I accept your document 1000 (send 1001 next). My initial document serial is 5000. Do you agree?"} \quad (\mathbf{SYN + ACK})
  • Step 3 (Alice acknowledges Bob): Alice writes back: "I acknowledge your document 5000 (send 5001 next). We are officially open for business!"(ACK)\text{"I acknowledge your document 5000 (send 5001 next). We are officially open for business!"} \quad (\mathbf{ACK})

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" (FIN\mathbf{FIN}).
  • Bob acknowledges, "Understood; I will sign your exit receipt" (ACK\mathbf{ACK}).
  • Bob can continue shipping his remaining inventory until he is done, after which Bob sends his own FIN\mathbf{FIN}, and Alice sends the final ACK\mathbf{ACK}.

💻 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:

  1. Confirm bidirectional communication reachability (Host A can reach Host B, and Host B can reach Host A).
  2. Establish synchronized starting sequence numbers (ISN\text{ISN}) so data bytes can be tracked without ambiguity.
  3. Exchange flow control window buffers (rwnd\text{rwnd}) and maximum segment sizes (MSS\text{MSS}).

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.

Space-Time Protocol Ladder
Step 1 of 3

TCP 3-Way Handshake Sequence & State Transitions

Interactive sequence diagram tracing Initial Sequence Number (ISN) negotiation and control flags

💡Click or hover any packet flight arrow, timer event, or step button to inspect protocol mechanics in real time
TIME (t)+∞
💻Active Opener
TCP Client (Host A)
Lifeline Rail (t ↓)
🖥️Passive Opener
TCP Server (Host B)
Lifeline Rail (t ↓)
1
2
3
Step 1 of 3client ➔ server

Frame transmitted across physical communication link.


Step-by-Step Handshake Protocol Analysis​

Step 1: Active Open (Client →\to Server)​

  • Control Flags: SYN=1,  ACK=0\text{SYN} = 1, \; \text{ACK} = 0.
  • Fields: Sequence Number=X\text{Sequence Number} = X (Client Initial Sequence Number, ISN). The Acknowledgment field contains no valid data.
  • State Transition: The client transitions from CLOSED to SYN_SENT.
  • Sequence Consumption: Although the SYN segment carries 00 bytes of application data, it consumes exactly 11 sequence number because it requires explicit acknowledgment.

Step 2: Passive Open Response (Server →\to Client)​

  • Control Flags: SYN=1,  ACK=1\text{SYN} = 1, \; \text{ACK} = 1.
  • Fields: Sequence Number=Y\text{Sequence Number} = Y (Server ISN), and Acknowledgment Number=X+1\text{Acknowledgment Number} = X + 1 (confirming receipt of client's byte XX).
  • State Transition: The server transitions from LISTEN to SYN_RCVD.
  • Sequence Consumption: Like the client SYN, the server SYN+ACK carries 00 bytes of application data but consumes exactly 11 sequence number.

Step 3: Connection Confirmation (Client →\to Server)​

  • Control Flags: SYN=0,  ACK=1\text{SYN} = 0, \; \text{ACK} = 1.
  • Fields: Sequence Number=X+1\text{Sequence Number} = X + 1, and Acknowledgment Number=Y+1\text{Acknowledgment Number} = Y + 1 (confirming receipt of server's byte YY).
  • State Transitions:
    • The client transitions to ESTABLISHED immediately upon sending this segment.
    • The server transitions from SYN_RCVD to ESTABLISHED upon receiving this segment.
  • Sequence Consumption: A pure ACK carries 00 data bytes and consumes 00 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?

Space-Time Protocol Ladder
Step 1 of 3

Why 2-Way Handshake Fails: The Delayed Duplicate SYN Hazard

How the 3rd handshake step empowers the client to abort phantom connections via RST

💡Click or hover any packet flight arrow, timer event, or step button to inspect protocol mechanics in real time
TIME (t)+∞
💻Active Host
Client (Host A)
Lifeline Rail (t ↓)
🖥️Passive Host
Server (Host B)
Lifeline Rail (t ↓)
1
2
3
Step 1 of 3client ➔ server

Frame transmitted across physical communication link.

  1. 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.
  2. Later, the old delayed SYN finally arrives at the server.
  3. 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 ESTABLISHED and sit idle forever waiting for data!
    • The client, having already finished its session, would ignore the server's ACK.
  4. With a 3-Way Handshake:
    • The server sends a SYN+ACK expecting the client's 3rd ACK.
    • The client receives an unexpected SYN+ACK for an old sequence number XX.
    • The client detects the anomaly and transmits an active RST (Reset) segment, forcing the server to safely abort and release its allocated memory!

✂️ 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.

Space-Time Protocol Ladder
Step 1 of 4

TCP 4-Way Connection Teardown & Half-Close Mechanics

Interactive sequence tracing graceful independent termination in each direction

💡Click or hover any packet flight arrow, timer event, or step button to inspect protocol mechanics in real time
TIME (t)+∞
💻Initiates Close
Client (Active Closer)
Lifeline Rail (t ↓)
🖥️Responds to Close
Server (Passive Closer)
Lifeline Rail (t ↓)
1
2
3
4
Step 1 of 4client ➔ server

Frame transmitted across physical communication link.


The Half-Close Connection State (SHUT_WR)​

  • When the client sends FIN and the server replies with ACK, 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 FIN segment.
  • 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.

Architecture Flow

SYN Flood Denial-of-Service Attack Cascade

How spoofed SYN packets deplete server kernel memory and block legitimate users

🤖Stage 1: Inundation

Spoofed SYN Avalanche

Attacker floods victim with thousands of SYN packets containing unreachable forged source IPs.

→
SYN Floods
💾Stage 2: Resource Drain

Kernel Backlog Saturation

Server allocates TCB state memory and SYN-ACK timers for phantom clients that never respond.

→
Queue 100% Full
🚫Stage 3: Service Outage

Legitimate Clients Blocked

Authentic client connection requests are dropped because the server's SYN queue has no free slots.

The Attack Mechanism:​

  1. An attacker transmits an overwhelming deluge of TCP SYN packets with randomized, spoofed source IP addresses.
  2. For each incoming SYN, the server allocates a Transmission Control Block (TCB) in kernel memory, allocates send/receive buffers, initializes timers, and returns a SYN+ACK to the spoofed IP.
  3. Because the spoofed IPs do not exist or ignore the unsolicited SYN+ACK, the 3rd ACK packet never arrives.
  4. 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:

  1. When the server receives a SYN, it allocates ZERO memory and creates NO kernel state block (TCB)!
  2. Instead, the server encodes all connection parameters inside its choice of Initial Sequence Number (YY): Y=Hash(Client IP,  Client Port,  Server IP,  Server Port,  Secret Key,  MSS Index)Y = \textbf{Hash}\Big(\text{Client IP}, \; \text{Client Port}, \; \text{Server IP}, \; \text{Server Port}, \; \text{Secret Key}, \; \text{MSS Index}\Big)
  3. The server transmits SYN+ACK with SEQ=Y\text{SEQ} = Y. If the client was spoofed, nothing happens, and zero server memory is consumed.
  4. If the client is legitimate, it returns the 3rd ACK with ACK_NUM=Y+1\text{ACK\_NUM} = Y + 1.
  5. The server subtracts 11 from the incoming acknowledgment number (Y+1−1=YY + 1 - 1 = Y), re-computes the hash, and verifies that the cookie matches!
  6. 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 PP (Client) and Host QQ (Server). Let XX and YY be 32-bit Initial Sequence Numbers (ISNs) selected by PP and QQ respectively. Suppose PP initiates a connection request by transmitting a TCP segment with SYN=1\text{SYN} = 1, SEQ=X\text{SEQ} = X, and ACK=0\text{ACK} = 0. If QQ accepts the connection request, determine the exact control flags, sequence number, acknowledgment number, and payload consumption in the segment returned by QQ to PP.

Step-by-Step Solution:

  1. Analyze Server Synchronization Requirements:
    Host QQ must accomplish two distinct protocol requirements in its response:
    • Synchronize its local sequence space: QQ asserts SYN=1\text{SYN} = 1 and announces its own initial sequence number: SEQ=Y\text{SEQ} = Y.
    • Acknowledge the client's request: QQ asserts ACK=1\text{ACK} = 1 to validate receipt of PP's initial segment.
  2. Determine Acknowledgment Number:
    Even though the initial connection request carries zero application payload bytes, RFC 793 dictates that a control SYN\text{SYN} segment consumes exactly 11 sequence number (XX). Therefore, QQ expects byte X+1X + 1 next: ACK Number=X+1\text{ACK Number} = X + 1
  3. Evaluate Remaining Flags:
    Because this segment belongs to the connection establishment phase, the FIN\text{FIN} flag remains cleared (FIN=0\text{FIN} = 0).
  4. Resulting Segment Parameters:
    SYN=1,SEQ=Y,ACK=1,ACK Number=X+1,FIN=0\text{SYN} = 1, \quad \text{SEQ} = Y, \quad \text{ACK} = 1, \quad \text{ACK Number} = X + 1, \quad \text{FIN} = 0

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:

  1. Loss of the server's SYN+ACK\text{SYN} + \text{ACK} segment in transit prevents connection establishment on that attempt.
  2. Loss of the client's final ACK\text{ACK} segment in transit permanently prevents connection establishment.
  3. During a standard passive open without loss, the server transitions through LISTEN→SYN_RCVD→ESTABLISHED\text{LISTEN} \to \text{SYN\_RCVD} \to \text{ESTABLISHED}.

Step-by-Step Solution:

  1. Evaluate Assertion 1 (Loss of Server SYN+ACK\text{SYN}+\text{ACK}):
    If the server's SYN+ACK\text{SYN}+\text{ACK} is dropped in the network, the client never learns the server's ISN (YY) and never dispatches the third ACK. The client remains stuck in SYN_SENT until its retransmission timer expires to retry. For that exchange attempt, no connection is established. Assertion 1 is Valid.
  2. Evaluate Assertion 2 (Loss of Final Client ACK\text{ACK}):
    Upon transmitting the final ACK\text{ACK}, the client immediately transitions to ESTABLISHED and can immediately send application data. Any subsequent data segment carries the ACK\text{ACK} flag set, which satisfies the server. Furthermore, the server's retransmission timer in SYN_RCVD will re-send SYN+ACK\text{SYN}+\text{ACK}, prompting the client to retransmit the ACK. Thus, establishment is not permanently precluded. Assertion 2 is Invalid.
  3. Evaluate Assertion 3 (Server State Sequence):
    In a normal passive open:
    • Server begins in LISTEN.
    • Receiving a client SYN causes the server to send SYN+ACK and enter SYN_RCVD.
    • Receiving the client's ACK completes the handshake and moves the server to ESTABLISHED.
    • Note that SYN_SENT is strictly an active-open client state and is never traversed by the server during passive open. Assertion 3 is Valid.

Example 3: Half-Close Connection Data Flow and Sequence Numbers​

Problem Statement:
Host AA and Host BB operate an established TCP connection. Host AA initiates a half-close by transmitting a FIN segment with sequence number SEQ=3000\text{SEQ} = 3000 and acknowledgment number ACK=5000\text{ACK} = 5000. Host BB receives this segment and acknowledges it. Subsequently, Host BB transmits 800800 bytes of application data to Host AA. Determine the exact sequence and acknowledgment numbers used across all three exchanges.

Step-by-Step Solution:

  1. Host BB's Acknowledgment of Host AA's FIN:
    Host AA's FIN consumes 11 sequence number (30003000). Host BB acknowledges this segment with: ACK Number=3000+1=3001,SEQ Number=5000\text{ACK Number} = 3000 + 1 = 3001, \quad \text{SEQ Number} = 5000 Host AA enters FIN_WAIT_2, and Host BB enters CLOSE_WAIT.
  2. Host BB's 800-Byte Data Segment:
    Because Host BB has not closed its outbound channel, it transmits its data starting at its current sequence number: SEQ Number=5000,Payload=800 bytes,ACK Number=3001\text{SEQ Number} = 5000, \quad \text{Payload} = 800\text{ bytes}, \quad \text{ACK Number} = 3001 The sequence numbers consumed by this data span [5000,5799][5000, 5799].
  3. Host AA's Acknowledgment of Data:
    Host AA receives the 800800 bytes and acknowledges the next expected byte: ACK Number=5000+800=5800,SEQ Number=3001\text{ACK Number} = 5000 + 800 = 5800, \quad \text{SEQ Number} = 3001 Host AA remains in FIN_WAIT_2 until Host BB concludes its transfer and sends its own FIN.

🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions
  • How many sequence numbers does a SYN segment consume?
    Exactly 11 sequence number, despite containing 00 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 00 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).
Common Interview Traps
  • 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 the SYN+ACK. When the client receives the duplicate SYN+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.

💬

Discussion & Doubts