Mastering TCP: How the Three‑Way Handshake and Four‑Way Teardown Work
This article explains the TCP three‑way handshake, the four‑step connection termination process, and the eleven TCP state transitions, detailing the role of SYN, ACK, and FIN flags and illustrating each step with clear diagrams and concise descriptions.
Three‑Way Handshake
TCP uses three flag bits—ACK, SYN, and FIN—to manage connections. SYN initiates a connection, ACK acknowledges received data, and FIN terminates a connection.
ACK: verification field
SYN: set to 1 to establish TCP connection
FIN: set to 1 to terminate TCP connection1. The client sends a SYN packet with a randomly generated sequence number (seq=x) and SYN=1.
2. The server replies with its own SYN=1, a new sequence number (seq=y), and an ACK=y+1 that acknowledges the client’s seq.
3. The client acknowledges the server’s SYN by sending ACK=x+1 while keeping SYN=1, completing the handshake.
Four‑Way Termination
1. The client sends a FIN packet with a random sequence number (seq=x) and FIN=1.
2. The server acknowledges the FIN with ACK=x+1 and its own sequence number (seq=y).
3. After ensuring all pending data is sent, the server sends its own FIN with a new sequence number (seq=z) and ACK=y+1.
4. The client acknowledges the server’s FIN with ACK=z+1 and a new sequence number (seq=h), completing the termination.
TCP State Diagram (11 States)
LISTEN : waiting for any incoming connection request.
SYN_SENT : client has sent a connection request and is awaiting a matching response.
SYN_RECEIVED : server has received a SYN and sent a SYN‑ACK, awaiting final ACK.
ESTABLISHED : connection is open and data can be exchanged.
FIN_WAIT_1 : client has sent FIN and is waiting for ACK or a FIN from the server.
FIN_WAIT_2 : client has received ACK for its FIN and is waiting for the server’s FIN.
CLOSE_WAIT : server has received FIN and is waiting for the application to close.
LAST_ACK : server has sent FIN and is waiting for the final ACK.
CLOSING : both sides have sent FIN but the ACK for the peer’s FIN is still pending.
TIME_WAIT : waiting long enough to ensure the remote TCP received the final ACK; also allows stray duplicate packets to expire.
CLOSED : no connection state (conceptual end state).
Author: IT_外卖小哥 – Source: https://blog.51cto.com/jinlong/2065461
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
