Sub topic 5
Opening and Closing a TCP Connection
This chapter assumes you know the TCP header fields from the previous chapter: sequence number, acknowledgement number, and the SYN, ACK, FIN, and RST flags. It also assumes you know what a socket is. TCP is connection-oriented, so both ends keep state and must agree on it before data flows and again before it stops. This chapter covers how that agreement is made and ended, and where GATE questions usually go wrong.
Why a connection needs setup
Each side of a TCP connection keeps a state record. The record holds the peer's address and port, the next sequence number to send, the next one expected, window sizes, and timers. Setup does three jobs:
- It tells the peer that you want to talk.
- It lets each side pick an initial sequence number (ISN) and tell the other.
- It lets each side confirm that the other can both send and receive.
TCP numbers bytes, not segments. Each direction has its own sequence space, so there are two ISNs, one per direction.
The three-way handshake
The client performs an active open. The server performs a passive open: it called listen and waits. In the socket API, the client's connect triggers the handshake, and the server's accept returns once the handshake has finished.
The steps are:
- The client sends a segment with SYN=1 and its ISN
x. - The server replies with SYN=1 and ACK=1. Its sequence number is its own ISN
y. Its acknowledgement number isx+1, the next byte it expects from the client. - The client sends ACK=1 with sequence number
x+1and acknowledgement numbery+1.
The SYN consumes one sequence number
A SYN carries no data, but it counts as one byte in the sequence space. That is why the acknowledgement is x+1 and not x. A FIN also consumes one sequence number. A pure ACK with no data consumes none.
If the client sends 100 bytes right after the handshake, its first data byte has sequence number x+1. The next data segment starts at x+101. The third handshake segment may carry data itself. Its sequence number is still x+1, and it is acknowledged as usual.
Why three steps and not two
With two steps, the server would consider the connection open after receiving a SYN. A delayed duplicate SYN from an old connection could then make the server open a connection that the client never asked for. The third segment fixes this. The client's ACK confirms that it saw the server's ISN, so a stale SYN gets no matching ACK and the server discards the half-open state.
Random ISNs also matter. Old segments from a previous connection on the same address pair should not be mistaken for new data. Random ISNs also make blind spoofing of a connection harder.
Handshake cost
Setup costs one round-trip time (RTT) before the client can send data. The client can start sending data with the third segment, so the application sees about 1 RTT of delay. A GATE question about "time to receive the first byte of data" typically adds this 1 RTT to one more RTT for the request and the first response bytes. Pay attention to whether the question counts the third handshake segment as part of the request.
Seeing the handshake from a program
The socket calls map onto the handshake. Run the server first, then the client in another terminal.
import socket
# Server: run this first, then run the client in another terminal.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
server.bind(("127.0.0.1", 5000))
server.listen()
conn, addr = server.accept()
with conn:
data = conn.recv(1024)
conn.sendall(data)import socket
# Client
with socket.create_connection(("127.0.0.1", 5000)) as client:
client.sendall(b"hello")
print(client.recv(1024))create_connection calls socket and connect. The connect call returns when the client has sent the final ACK. accept hands the server a new socket for this one connection. The listening socket stays open for more clients. The client's operating system picks an ephemeral port as the source port.
Connection states
TCP tracks its progress with a state machine. These states appear in GATE questions and in the output of tools like netstat and ss.
Closing a connection
TCP is full duplex, so each direction is closed on its own. Each direction needs a FIN and an ACK. This is why a normal close takes four segments.
- The side that closes first sends FIN. Its state becomes FINWAIT1.
- The other side acknowledges the FIN and enters CLOSEWAIT. The first side moves to FINWAIT_2. The connection is now half-closed. The passive side can still send data, and the active side must still accept and acknowledge it.
- When the passive side's application calls close, it sends its own FIN and enters LAST_ACK.
- The active side acknowledges that FIN and enters TIME_WAIT. The passive side moves to CLOSED when it gets the ACK.
If the passive side has no more data to send, it can send its ACK and its FIN in the same segment. The sequence then has three segments, not four. The four-segment form is the general case.
TIME_WAIT
The side that closes first waits for 2 × MSL (maximum segment lifetime) before reaching CLOSED. MSL is the longest time a segment is assumed to live in the network. Common values are 30 seconds or 60 seconds, so the wait is one to two minutes. There are two reasons:
- The last ACK may be lost. The passive side would then resend its FIN. The active side must still be around to acknowledge it again.
- Delayed segments from this connection must expire before the same address and port pair is reused. Otherwise an old segment could be taken as part of a new connection.
In practice, a busy server that closes many connections itself can accumulate thousands of sockets in TIMEWAIT. This is why many servers let the client close first, or enable address reuse (`SOREUSEADDR`) so a restarted server can bind to its port while old connections are still waiting.
Abrupt close and refusal: RST
A segment with RST=1 tears down a connection immediately, with no handshake and no waiting.
- If a SYN arrives for a port with no listening socket, the host answers with RST. The client sees "connection refused".
- A program can send RST instead of FIN to abort a connection and discard unsent data.
- A segment that arrives for a connection that does not exist gets an RST in reply.
UDP has no such mechanism. For a closed UDP port, the host sends an ICMP "port unreachable" message instead.
Simultaneous open and close
Two hosts can send SYN to each other at the same moment. Each moves from SYNSENT to SYNRCVD and then to ESTABLISHED, and the result is one connection. Two hosts can also close at the same moment, with both sending FIN. Both go through CLOSING and then TIME_WAIT. These cases are rare in practice but appear in the state machine.
Common errors
- Forgetting that SYN and FIN each use one sequence number. The acknowledgement for a SYN with sequence
xisx+1. For a FIN with sequenceuit isu+1. If the FIN segment carriesndata bytes, the acknowledgement isu+n+1. - Mixing the two ISNs. The client's sequence number in segment 3 is
x+1, noty+1. Its acknowledgement number isy+1. - Saying the server enters ESTABLISHED when it sends SYN+ACK. It enters ESTABLISHED only when it receives the final ACK. Until then it is in SYN_RCVD.
- Placing TIME_WAIT on the wrong side. It belongs to the side that sent the first FIN, not always the client.
- Confusing half-open and half-closed. A half-open connection is one where one side has crashed or never finished the handshake. A half-closed connection is one where one direction has been shut down in an orderly way and the other still works.
- Counting segments. Setup is three segments. Close is four, or three if the passive side combines its ACK and FIN.
Worked example
A client with ISN 2000 connects to a server with ISN 5000. The client sends 300 bytes, the server replies with 100 bytes, and then the client closes first. Assume the server closes right after, and no segment is lost.
| Segment | Direction | Flags | Seq | Ack |
|---|---|---|---|---|
| 1 | C to S | SYN | 2000 | - |
| 2 | S to C | SYN, ACK | 5000 | 2001 |
| 3 | C to S | ACK | 2001 | 5001 |
| 4 | C to S | ACK (300 bytes) | 2001 | 5001 |
| 5 | S to C | ACK (100 bytes) | 5001 | 2301 |
| 6 | C to S | FIN, ACK | 2301 | 5101 |
| 7 | S to C | ACK | 5101 | 2302 |
| 8 | S to C | FIN, ACK | 5101 | 2302 |
| 9 | C to S | ACK | 2302 | 5102 |
Segment 3 carries no data, so it uses no sequence number. Segment 4 therefore starts at 2001 as well. After 300 bytes, the client's next sequence number is 2301. The server's reply starts at 5001 and ends at 5100, so the next is 5101. The FIN from the client uses 2301, so the server acknowledges 2302. Segments 7 and 8 could be merged into one FIN+ACK segment, since the server has nothing more to send.
Exercise
A client opens a TCP connection with ISN 8000 and the server uses ISN 1200. After the handshake, the client sends one segment of 500 bytes and then sends a FIN with no data. What are the sequence number of the client's FIN and the acknowledgement number the server sends for it?
Show answer
The SYN consumes sequence number 8000, so the first data byte is 8001. The 500 bytes occupy 8001 to 8500. The FIN therefore has sequence number 8501. The server acknowledges it with 8502, because the FIN consumes one sequence number.
Exercise
Which side enters TIME_WAIT when the server calls close first, and why does that side wait for 2 MSL?
Show answer
The server enters TIME_WAIT, because the side that sends the first FIN is the active closer. It waits so that it can re-acknowledge a retransmitted FIN if its last ACK was lost, and so that old segments from this connection expire before the same address and port pair is reused.