Sub topic 7
Opening a connection: the three-way handshake
This chapter assumes you know the four-layer model, what an IP address and packet are, and the difference between a port and a socket from earlier chapters. It also assumes you can read short Python programs. It covers how TCP sets up a connection, what the two sides agree on, which states they pass through, and what you see in your program when the setup works or fails.
Why TCP needs a handshake
IP delivers packets on a best-effort basis. A packet can be lost, duplicated, delayed or reordered. TCP builds a reliable, ordered byte stream on top of that, and it needs shared state at both ends to do so:
- Each side must know the other exists and is willing to talk.
- Each side must pick a starting sequence number for its outgoing bytes, and the other side must learn it.
- Both sides must agree on options such as segment size and window scaling.
The three-way handshake creates this state with three segments. UDP has no equivalent step. A UDP sender simply transmits, and it never learns whether anyone is listening.
The three segments
A TCP segment carries flag bits in its header. The handshake uses two of them: SYN (synchronize sequence numbers) and ACK (the acknowledgment field is valid).
- SYN. The client sends a segment with SYN set and its initial sequence number (ISN) in the sequence field.
- SYN-ACK. The server replies with SYN and ACK both set. It sends its own ISN and acknowledges the client's ISN plus one.
- ACK. The client sends a segment with ACK set, acknowledging the server's ISN plus one.
The sequence numbers here are small for readability. Real ISNs are 32-bit values that look random.
| Step | Sender | Flags | Seq | Ack | Sender state afterward |
|---|---|---|---|---|---|
| 1 | Client | SYN | 1000 | none | SYN-SENT |
| 2 | Server | SYN, ACK | 5000 | 1001 | SYN-RECEIVED |
| 3 | Client | ACK | 1001 | 5001 | ESTABLISHED |
The ack value is always "the next sequence number I expect from you." A SYN consumes one sequence number even though it carries no data. That is why the server acknowledges 1001, not 1000. A FIN, which closes a connection, also consumes one number.
Once the client sends the third segment, it considers the connection established. The server reaches ESTABLISHED when that ACK arrives. The client's first data segment can ride on the third segment or follow it immediately.
Why three segments and not two
Two segments would let the server confirm it heard the client. The server would still not know that the client heard the server's ISN. Each direction of a TCP connection needs its own ISN to be sent and acknowledged. That is four pieces of information: SYN and ACK in each direction. The server's SYN and its ACK of the client's SYN travel in one segment, which brings the count down to three.
A second reason is stale packets. If an old duplicate SYN from a previous connection arrives at the server, the server answers with a SYN-ACK. The client did not start that connection, so it does not recognize the acknowledged number and replies with a RST (reset). The server drops the half-open connection. A two-segment handshake could not catch this.
Choosing the initial sequence number
The ISN is not zero or one. Two reasons drive this:
- Old segments. A delayed segment from an earlier connection with the same address and port pairs could be mistaken for data of the new connection. A different starting point makes that unlikely.
- Spoofing. If an attacker could predict the ISN, they could inject segments into a connection from a forged address. Modern operating systems derive the ISN from a keyed hash of the connection's addresses and ports plus a clock, as RFC 6528 recommends.
What else the handshake negotiates
The SYN and SYN-ACK segments carry TCP options. The common ones are:
- MSS (maximum segment size). The largest amount of data each side is willing to receive in one segment. It is usually the link's MTU minus the IP and TCP headers, so 1460 bytes on a 1500-byte Ethernet MTU.
- Window scale. A multiplier that extends the 16-bit receive window field. A later chapter on flow control explains why this matters.
- SACK permitted. Allows selective acknowledgments, which help recovery from loss.
- Timestamps. Support round-trip time measurement and protection against wrapped sequence numbers.
Options appear only in the SYN and SYN-ACK. If the client does not offer an option in its SYN, the server cannot use it in the reply. For window scaling this means both sides must offer it, or neither can use it.
Handshake and the sockets API
The handshake happens inside the operating system's kernel. Your program only calls socket functions.
listen()puts the server socket into LISTEN. The kernel then answers incoming SYNs without involving your program.connect()on the client sends the SYN and blocks until the handshake finishes or fails.accept()on the server takes an already established connection from a queue. It does not perform the handshake.
The kernel keeps two queues per listening socket. Half-open connections (SYN received, final ACK not yet seen) wait in the SYN queue. Fully established connections wait in the accept queue until your program calls accept(). The backlog argument to listen() limits the accept queue, and the kernel may also cap it with a system setting.
The following program shows that connect() can succeed before the server calls accept():
import socket
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(("127.0.0.1", 0)) # port 0: the OS picks a free port
srv.listen(5)
port = srv.getsockname()[1]
cli = socket.create_connection(("127.0.0.1", port), timeout=2)
print("connect() returned; the server has not called accept() yet")
print("client side:", cli.getsockname(), "->", cli.getpeername())
conn, addr = srv.accept()
print("accept() returned a connection from", addr)
conn.close()
cli.close()
srv.close()This single-threaded program works because the kernel completes the handshake on behalf of the listening socket. The client's connect() returns as soon as it receives the SYN-ACK and sends its ACK.
Handshake failures
What your program sees depends on how the handshake fails.
| Situation | What happens on the wire | What the client sees |
|---|---|---|
| Nothing listens on the port | The host replies to the SYN with a RST | `ConnectionRefusedError` immediately |
| A firewall silently drops the SYN | No reply at all | The SYN is retransmitted, then a timeout |
| The host is down or unreachable | No reply, or an ICMP unreachable message | Timeout, or a "no route" or "unreachable" error |
| The accept queue is full | The server may drop the final ACK or the SYN | Slow connects or timeouts |
A lost SYN is retransmitted after a timer. Many systems start at about one second and double the wait each time (1 s, 2 s, 4 s, and so on). Linux defaults to six retries, so a connect to a black-holed address can block for over a minute unless you set a timeout. The difference between "refused" and "timed out" is useful when diagnosing a problem. A refusal means the host is reachable and nothing listens. A timeout means something drops your packets or the host is unreachable.
import socket
def try_connect(host, port, timeout):
try:
with socket.create_connection((host, port), timeout=timeout):
return "connected"
except ConnectionRefusedError:
return "refused: a RST came back"
except socket.timeout:
return "timed out: no reply"
except OSError as err:
return f"other error: {err}"
# Assumes nothing listens on local port 9000.
print(try_connect("127.0.0.1", 9000, 3))
# 10.255.255.1 is usually unroutable, so the SYN gets no answer.
print(try_connect("10.255.255.1", 80, 3))The second result depends on your network. Some networks return an immediate "unreachable" error instead of a timeout, which the last except branch reports.
SYN floods and SYN cookies
Between the SYN and the final ACK, the server keeps state for each half-open connection. In a SYN flood, an attacker sends many SYNs, often from forged source addresses. The server answers each one and waits for ACKs that never come. The SYN queue fills and real clients are refused.
SYN cookies are the standard defense. When the queue is under pressure, the server stores nothing. It encodes the needed information, mostly a hash of the addresses, ports and a timestamp, into the ISN of its SYN-ACK. A legitimate client's ACK carries that number plus one back, and the server rebuilds the connection state from it. The cost is that some options, such as window scaling, may be lost for connections accepted this way unless they are encoded as well.
Simultaneous open
Rarely, both sides send a SYN to each other at the same time. Each moves to SYN-RECEIVED, then they exchange SYN-ACKs, and one connection results. This is allowed by the protocol but almost never occurs in ordinary client-server programs. Techniques such as TCP hole punching in peer-to-peer software use it deliberately.
Cost of the handshake
The handshake takes one round trip before the client can send its first byte of data. On a link with a 100 ms round trip, every new connection pays 100 ms. Applications reduce this cost by reusing connections (keep-alive, connection pools). TCP Fast Open lets data ride in the SYN for repeat connections, though it has limited deployment. Encryption adds more round trips on top: classic TLS adds one or two, and QUIC, which runs over UDP, combines transport and cryptographic setup.
Exercise
A client's SYN carries seq=7000. The server's ISN is 42000. Write the sequence and acknowledgment numbers in the SYN-ACK and in the final ACK.
Show answer
The SYN-ACK has seq=42000 and ack=7001. The final ACK has seq=7001 and ack=42001. Each SYN uses up one sequence number, so each side acknowledges the other's ISN plus one.
Exercise
Your program calls connect() to a server. Case A returns an error after a few milliseconds. Case B blocks for about 20 seconds and then fails. Which of these is likely a closed port and which is likely a firewall dropping packets, and why?
Show answer
Case A is likely a closed port. The host answered the SYN with a RST, which gives an immediate ConnectionRefusedError. Case B is likely a firewall or an unreachable host. No reply came back, so the client retransmitted the SYN with growing delays until it gave up.
Exercise
A server calls listen(5) but never calls accept(). Can a client still connect() successfully? Explain what limits this.
Show answer
Yes. The kernel completes the handshake for the listening socket and places the established connection in the accept queue. Once that queue is full (about the backlog size), further handshakes are delayed or dropped, and clients start to see slow connects or timeouts.