TExcelTAD
Home › Computer Networking › TCP Handshake & Teardown

TCP Handshake & Teardown

Before any data flows, the two ends of a TCP connection agree to talk and exchange their initial sequence numbers (ISNs). At the end, each side closes its direction of the stream. Both procedures are driven by a state machine that every TCP implementation follows.

The 3-way handshake

text
Client                                     Server (LISTEN)
  |  SYN seq=x                         --->  |
  |                                          |  SYN-RECEIVED
  |  <---    SYN+ACK seq=y ack=x+1           |
  |  ESTABLISHED                             |
  |  ACK seq=x+1 ack=y+1               --->  |
  |                                          |  ESTABLISHED

Why three messages? Each side has to send its own ISN and hear it acknowledged. The server's SYN and its ACK of the client's SYN are combined in one segment, so three messages are enough.

python · try it yourself
def handshake(client_isn, server_isn):
    log = []
    log.append(("client", "SYN", client_isn, None))
    log.append(("server", "SYN+ACK", server_isn, client_isn + 1))
    log.append(("client", "ACK", client_isn + 1, server_isn + 1))
    for who, flags, seq, ack in log:
        arrow = "-->" if who == "client" else "<--"
        ack_text = f" ack={ack}" if ack is not None else ""
        print(f"{arrow} {flags:<8} seq={seq}{ack_text}")
    return client_isn + 1, server_isn + 1

c_next, s_next = handshake(client_isn=1000, server_isn=5000)
print("client's first data byte will be", c_next, "| server's first data byte will be", s_next)
--> SYN      seq=1000
<-- SYN+ACK  seq=5000 ack=1001
--> ACK      seq=1001 ack=5001
client's first data byte will be 1001 | server's first data byte will be 5001

The handshake costs one full round trip before the client can send its request. For a server 100 ms away, that's 100 ms of waiting on every new connection, which is why browsers reuse connections and why TLS 1.3 and QUIC work hard to cut round trips.

Closing: the 4-way teardown

TCP is full duplex, so each direction is closed separately. The side that closes first sends FIN; the other side acknowledges it, may keep sending data, and later sends its own FIN.

text
Client (active close)                      Server
  |  FIN                                ---> |  CLOSE-WAIT (app still may send)
  |  FIN-WAIT-1                              |
  |  <---                               ACK  |
  |  FIN-WAIT-2                              |
  |  <---                               FIN  |  LAST-ACK
  |  TIME-WAIT                               |
  |  ACK                                ---> |  CLOSED
  |  (waits 2 x MSL, then CLOSED)            |

The state machine in code

Here is a simplified TCP state machine covering the normal open and close paths. Each entry maps (state, event) to (new state, segment to send):

python · try it yourself
TRANSITIONS = {
    ("CLOSED",      "app: connect"): ("SYN-SENT",    "SYN"),
    ("LISTEN",      "recv SYN"):     ("SYN-RCVD",    "SYN+ACK"),
    ("SYN-SENT",    "recv SYN+ACK"): ("ESTABLISHED", "ACK"),
    ("SYN-RCVD",    "recv ACK"):     ("ESTABLISHED", None),
    ("ESTABLISHED", "app: close"):   ("FIN-WAIT-1",  "FIN"),
    ("ESTABLISHED", "recv FIN"):     ("CLOSE-WAIT",  "ACK"),
    ("FIN-WAIT-1",  "recv ACK"):     ("FIN-WAIT-2",  None),
    ("FIN-WAIT-2",  "recv FIN"):     ("TIME-WAIT",   "ACK"),
    ("CLOSE-WAIT",  "app: close"):   ("LAST-ACK",    "FIN"),
    ("LAST-ACK",    "recv ACK"):     ("CLOSED",      None),
    ("TIME-WAIT",   "timeout 2MSL"): ("CLOSED",      None),
}

class Tcp:
    def __init__(self, name, state):
        self.name, self.state = name, state

    def handle(self, event):
        key = (self.state, event)
        if key not in TRANSITIONS:
            raise ValueError(f"{self.name}: event {event!r} not valid in {self.state}")
        new_state, send = TRANSITIONS[key]
        arrow = f"--{event}-->"
        print(f"{self.name:<6} {self.state:<11} {arrow:<20} {new_state:<11} send: {send or '-'}")
        self.state = new_state

client, server = Tcp("client", "CLOSED"), Tcp("server", "LISTEN")
for who, event in [(client, "app: connect"), (server, "recv SYN"), (client, "recv SYN+ACK"),
                   (server, "recv ACK"),
                   (client, "app: close"), (server, "recv FIN"), (client, "recv ACK"),
                   (server, "app: close"), (client, "recv FIN"), (server, "recv ACK"),
                   (client, "timeout 2MSL")]:
    who.handle(event)

try:
    Tcp("x", "LISTEN").handle("app: close")
except ValueError as err:
    print("error:", err)
client CLOSED      --app: connect-->    SYN-SENT    send: SYN
server LISTEN      --recv SYN-->        SYN-RCVD    send: SYN+ACK
client SYN-SENT    --recv SYN+ACK-->    ESTABLISHED send: ACK
server SYN-RCVD    --recv ACK-->        ESTABLISHED send: -
client ESTABLISHED --app: close-->      FIN-WAIT-1  send: FIN
server ESTABLISHED --recv FIN-->        CLOSE-WAIT  send: ACK
client FIN-WAIT-1  --recv ACK-->        FIN-WAIT-2  send: -
server CLOSE-WAIT  --app: close-->      LAST-ACK    send: FIN
client FIN-WAIT-2  --recv FIN-->        TIME-WAIT   send: ACK
server LAST-ACK    --recv ACK-->        CLOSED      send: -
client TIME-WAIT   --timeout 2MSL-->    CLOSED      send: -
error: x: event 'app: close' not valid in LISTEN

The full RFC state machine has 11 states and also covers simultaneous open, simultaneous close and resets.

TIME-WAIT

The side that closes first waits in TIME-WAIT for twice the Maximum Segment Lifetime (typically 60 s on Linux) before forgetting the connection. This makes sure that:

  1. if the final ACK is lost, it can be resent when the peer retransmits its FIN, and
  2. stray delayed segments from the old connection die before the same 5-tuple can be reused.

On a busy server that initiates many short connections, thousands of sockets in TIME-WAIT are normal:

python · try it yourself
connections_per_second = 500
time_wait_seconds = 60
print("sockets in TIME-WAIT at steady state:", connections_per_second * time_wait_seconds)

ephemeral_ports = 60999 - 32768 + 1
print("max new connections/s to ONE backend ip:port:", ephemeral_ports // time_wait_seconds)
sockets in TIME-WAIT at steady state: 30000
max new connections/s to ONE backend ip:port: 470

That second number is why proxies use connection pooling (keep connections open and reuse them) instead of opening a new connection per request.

Reset

A RST segment aborts a connection with no handshake. You see one when:

  • you connect to a port where nothing is listening (the client reports "Connection refused"),
  • an application closes a socket while unread data is still in its buffer,
  • a firewall or middlebox kills a connection.
bash
curl -v http://127.0.0.1:8081/

Sample output:

text
*   Trying 127.0.0.1:8081...
* connect to 127.0.0.1 port 8081 failed: Connection refused
* Failed to connect to 127.0.0.1 port 8081 after 0 ms: Couldn't connect to server
curl: (7) Failed to connect to 127.0.0.1 port 8081 after 0 ms: Couldn't connect to server

"Connection refused" (RST came back) and "Connection timed out" (nothing came back, often a firewall silently dropping) point to different problems, so read the error carefully.

SYN floods

A server in SYN-RCVD has reserved memory for a half-open connection. A SYN flood attack sends huge numbers of SYNs from spoofed addresses and never completes the handshake, filling the server's queue. SYN cookies defend against it: the server encodes the connection details into its ISN and keeps no state until the final ACK proves the client is real.

bash
ss -tan state time-wait | head -3

Sample output:

text
Recv-Q Send-Q   Local Address:Port      Peer Address:Port
0      0         192.168.1.20:51514    93.184.215.14:443
0      0         192.168.1.20:51522    93.184.215.14:443

Go further: SYN Floods and SYN Cookies shows how a half-open backlog fills up and how SYN cookies keep it empty.

Test yourself

What are the three segments of the TCP handshake, in order?

  1. SYN, ACK, FIN
  2. SYN, SYN+ACK, ACK
  3. ACK, SYN, SYN+ACK
  4. SYN, FIN, ACK

Which side of a connection enters TIME-WAIT?

  1. The side that closes first (active close)
  2. The server, always
  3. The side that receives the first FIN
  4. Both sides

A client gets 'Connection refused'. What did it most likely receive?

  1. Nothing at all
  2. A SYN+ACK
  3. A RST in reply to its SYN
  4. An ICMP echo reply