Catalog My learning Blog
Computer Networking for Developers: TCP, DNS, HTTP, TLS · Phase 2 · Lesson 8 · 5 min read

TCP Three-Way Handshake Explained

On this page
  1. What TCP promises
  2. The TCP three-way handshake
  3. Sequence numbers, ACKs and retransmission
  4. TCP connection states: CLOSE_WAIT and TIME_WAIT
  5. Connection refused vs connection timed out
  6. Check yourself

What TCP promises

IP delivers packets on a best-effort basis: they can be lost, duplicated or arrive out of order. TCP (Transmission Control Protocol) builds a reliable, ordered byte stream on top. Your HTTP client writes bytes; the server reads the same bytes in the same order, or the connection fails with an error. Databases, HTTP/1.1 and HTTP/2, SSH and most of what you use run over TCP.

The TCP three-way handshake

Before any data flows, both sides agree to talk and pick starting sequence numbers:

  1. SYN: the client sends a segment with the SYN flag and a random initial sequence number, say x.
  2. SYN-ACK: the server replies with its own SYN (sequence y) and acknowledges x + 1.
  3. ACK: the client acknowledges y + 1. The connection is established.

That costs one full round trip before the first byte of the request. On a 100 ms path, that's 100 ms just to connect, which is why connection reuse matters (Day 13) and why TLS 1.3 and QUIC work hard to cut round trips (Days 14 and 16).

The three-way handshake opening a connection and the FIN/ACK exchange closing it, with sequence and acknowledgment numbers at each step.
The three-way handshake opening a connection and the FIN/ACK exchange closing it, with sequence and acknowledgment numbers at each step.

Sequence numbers, ACKs and retransmission

  • Sequence numbers count bytes, so the receiver can put segments back in order and drop duplicates.
  • Acknowledgments tell the sender what has arrived ("I have everything up to byte 5,001").
  • Retransmission: if no acknowledgment arrives within the retransmission timeout (RTO, computed from measured round-trip times), or the receiver signals a gap with duplicate acknowledgments, the sender resends.
  • Checksums catch corrupted segments, which are dropped and retransmitted.

Here's how those pieces work together when a packet goes missing. A client sends 3,000 bytes as three segments of 1,000 bytes. Sequence numbers count bytes, so the segments start at bytes 1, 1001 and 2001 (relative to the random starting number). Each acknowledgment names the next byte the receiver expects:

StepEventThe receiver says
1Segment with bytes 1 to 1000 arrivesACK 1001: "send me 1001 next"
2Segment with bytes 1001 to 2000 is lostNothing; it never arrived
3Segment with bytes 2001 to 3000 arrivesACK 1001 again: "I still need 1001"
4Later segments arrive too, each answered with ACK 1001 againAfter three duplicate ACKs, the sender concludes 1001 to 2000 was lost and resends it straight away
5The resent segment arrivesACK 3001: "I now have everything up to 3000"

Three duplicate ACKs trigger this fast retransmit, which is much quicker than waiting for the timeout. Notice step 3, though. The receiver already holds bytes 2001 to 3000, but it can't hand them to the application, because bytes 1001 to 2000 come first.

The cost: one lost packet stalls everything behind it until it's resent, since data must be delivered in order. That's head-of-line blocking, important on Day 14.

TCP connection states: CLOSE_WAIT and TIME_WAIT

This script opens a local connection, closes the client side, then the server side, printing the states from netstat after each step:

Code
# tcpstates.py: open a local TCP connection, close it, and look at the states left behind
import socket, subprocess, time
srv = socket.socket(); srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 9098)); srv.listen()
cli = socket.create_connection(("127.0.0.1", 9098))   # SYN, SYN-ACK, ACK happen here
conn, _ = srv.accept()
show = lambda: print(subprocess.run("netstat -an -p tcp | grep 9098", shell=True, capture_output=True, text=True).stdout)
show()
cli.close(); time.sleep(0.2)   # client sends FIN; the server hasn't closed yet
show()
conn.close(); time.sleep(0.2)  # server closes too; the side that closed first waits in TIME_WAIT
show()
Code
127.0.0.1.9098    127.0.0.1.58570   ESTABLISHED
127.0.0.1.58570   127.0.0.1.9098    ESTABLISHED
127.0.0.1.9098    *.*               LISTEN

127.0.0.1.9098    127.0.0.1.58570   CLOSE_WAIT
127.0.0.1.58570   127.0.0.1.9098    FIN_WAIT_2
127.0.0.1.9098    *.*               LISTEN

127.0.0.1.9098    *.*               LISTEN
127.0.0.1.58570   127.0.0.1.9098    TIME_WAIT

What the states mean in production:

  • CLOSE_WAIT means the other side closed, but your program hasn't. Thousands of them signal a bug: code that never closes its sockets.
  • TIME_WAIT is normal. The side that closes first waits (often 30 to 120 seconds) so delayed packets from the old connection can't confuse a new one on the same ports. Huge numbers on a client usually mean it opens a new connection per request; reuse connections instead.

Connection refused vs connection timed out

Code
import socket, time
for host, port in [("127.0.0.1", 9), ("10.255.255.1", 80)]:
    t = time.time()
    try: socket.create_connection((host, port), timeout=3)
    except Exception as e: print(f"{host}:{port:<4} {type(e).__name__:<22} after {time.time()-t:.2f}s")
Code
127.0.0.1:9    ConnectionRefusedError after 0.00s
10.255.255.1:80   timeout                after 3.00s
  • Refused, instantly: the host is reachable and answered with a TCP reset (RST), because nothing listens on that port. Check the service and its port.
  • Timed out: no answer at all. The host is down, unreachable, or a firewall silently drops the SYN. Check routing and firewall rules (Day 18).

Check yourself

The three-way handshake, SYN, SYN-ACK, ACK, takes one full round trip before the client can send its first data byte, and TLS adds another round trip or more on top. Connection reuse and keep-alive avoid paying it for every request.

Clients closed their side, but the server application never called close on those sockets. It's leaking connections, often from a code path that doesn't close a response or return a connection to its pool, and it will eventually run out of file descriptors.

The host is reachable and answered with a reset: nothing is listening on that port, or a firewall actively rejects. A timeout instead means packets are being dropped silently or the host is unreachable.

It acknowledges 1001, the next byte it expects. The application can't read 2001 to 3000 until the missing bytes arrive, because TCP delivers bytes strictly in order.

The side that closes first waits about twice the maximum segment lifetime so delayed packets from the old connection can't be mistaken for a new one using the same ports, and so its final ACK can be resent.