Sub topic 12
Closing a Connection and TCP States
This chapter assumes you know the three-way handshake, sequence and acknowledgment numbers, and the basic sockets calls (connect, accept, recv, close). It covers how a TCP connection ends, what each side's state machine does along the way, and which teardown problems show up in real programs.
Why closing is harder than opening
A TCP connection carries two independent byte streams, one in each direction. Each direction has to be shut down separately. The FIN flag marks the end of one direction: "I will send no more data." The receiver of a FIN acknowledges it, and its own sending direction stays open until it sends its own FIN.
So a normal close takes four segments:
- Side A sends
FIN. - Side B sends
ACKfor it. - Side B sends
FINwhen its application is done. - Side A sends
ACKfor thatFIN.
A FIN uses up one sequence number, like a SYN. That is why the acknowledgment is the FIN's sequence number plus one.
The side that sends the first FIN is the active closer. The other side is the passive closer. Either endpoint can be the active closer. The roles do not depend on who opened the connection.
If the passive side has nothing left to send, it can combine its ACK and FIN in one segment. The teardown then takes three segments. Many stacks do this.
Half-close
Because the directions are independent, an application can close only its sending direction. In Python this is shutdown(socket.SHUT_WR). The peer's recv returns b"", which signals end of stream. The peer can still send, and you can still read.
close() is different. It releases the socket's descriptor and, once the last reference is gone, closes both directions. After close() you can no longer read the peer's remaining data.
Half-close is how a client can send a whole request, signal "that's all", and then read a reply of unknown length. This program runs in a single process.
import socket
import threading
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()
port = srv.getsockname()[1]
def serve():
conn, _ = srv.accept()
with conn:
received = b""
while True:
data = conn.recv(1024)
if not data: # client sent FIN
break
received += data
# The client's sending side is closed, but ours is still open.
conn.sendall(b"got " + str(len(received)).encode() + b" bytes")
t = threading.Thread(target=serve)
t.start()
with socket.create_connection(("127.0.0.1", port)) as c:
c.sendall(b"request body")
c.shutdown(socket.SHUT_WR) # send FIN, keep reading
print(c.recv(1024)) # b'got 12 bytes'
print(c.recv(1024)) # b'' because the server has now closed too
t.join()
srv.close()Here the client sends the first FIN, so the client is the active closer. It is the side that ends up in TIME_WAIT.
The TCP states
The TCP state machine records where each endpoint is in the lifecycle. The states you meet during teardown are the ones below.
| State | Meaning |
|---|---|
| `ESTABLISHED` | Handshake done. Data flows both ways. |
| `FIN_WAIT_1` | We sent `FIN` and are waiting for its `ACK`. |
| `FIN_WAIT_2` | Our `FIN` was acknowledged. We wait for the peer's `FIN`. |
| `CLOSE_WAIT` | The peer's `FIN` arrived and was acknowledged. We are waiting for our application to close. |
| `LAST_ACK` | We sent our `FIN` after `CLOSE_WAIT` and are waiting for its `ACK`. |
| `CLOSING` | Both sides sent `FIN` at the same time, and ours is not yet acknowledged. |
| `TIME_WAIT` | Both `FIN`s are acknowledged. We wait before releasing the connection. |
| `CLOSED` | No connection exists. |
Two details are worth knowing.
- Simultaneous close. If both applications close at the same moment, each side receives a
FINwhile still inFIN_WAIT_1. Both move toCLOSING, then toTIME_WAIT. Both sides are active closers. - Combined
FIN+ACK. If theACKof ourFINarrives together with the peer'sFIN, the state goes straight fromFIN_WAIT_1toTIME_WAIT.
TIME_WAIT
After the active closer sends the final ACK, it does not drop the connection. It stays in TIME_WAIT for twice the maximum segment lifetime (MSL), the longest time a segment is assumed to survive in the network. RFC 9293 suggests an MSL of 2 minutes, so 4 minutes. Linux uses a fixed 60 seconds for TIME_WAIT.
There are two reasons for the wait:
- The last
ACKmay be lost. If it is, the passive closer retransmits itsFIN. The active closer must still be around to answer it with anotherACK. If it had already forgotten the connection, it would answer with a reset, and the passive side would see an error instead of a clean close. - Old segments must die. A delayed segment from the old connection could arrive after a new connection reuses the same four-tuple (source address, source port, destination address, destination port). Waiting 2 × MSL ensures old duplicates have expired.
TIME_WAIT is not a bug. A few thousand entries cost little memory. It becomes a problem on a client or proxy that opens very many short connections to one destination address and port. It can then run out of ephemeral source ports. The usual fixes are connection reuse (keep-alive, pooling), a wider ephemeral port range, or letting the server close first so the TIME_WAIT cost falls on the server side.
The server in the chapter's echo example sets SO_REUSEADDR. Without it, restarting the server soon after a crash can fail with "Address already in use", because connections from the old listener port are still in TIME_WAIT. With the option set, bind succeeds despite those leftovers.
Abortive close with RST
A FIN is a polite close. A RST (reset) is an abort. It discards the connection state immediately, with no TIME_WAIT and no retransmission. The peer sees a connection reset error.
Common causes of a RST:
- A segment arrives for a port with no listener, or for a connection the host does not know.
- An application calls
close()while unread data is still in its receive buffer. Many stacks then sendRSTinstead ofFIN. - The application asks for it with
SO_LINGERset to on, with a timeout of zero.
import socket
import struct
import threading
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(("127.0.0.1", 0))
srv.listen()
port = srv.getsockname()[1]
def serve():
conn, _ = srv.accept()
with conn:
try:
conn.recv(1024)
except ConnectionResetError:
print("server: connection reset by peer")
t = threading.Thread(target=serve)
t.start()
c = socket.create_connection(("127.0.0.1", port))
# linger on, timeout 0: close() sends RST and skips TIME_WAIT
c.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
c.close()
t.join()
srv.close()A reset also throws away any data the peer had sent but the application had not yet read. Use it only for real aborts, not for ordinary closes.
Teardown problems you will see
Stuck in CLOSE_WAIT
CLOSE_WAIT means the peer closed and the kernel acknowledged it, but your application never called close(). The kernel cannot move on without you. Many sockets stuck in CLOSE_WAIT almost always mean a program bug, such as a missing close() on an error path or a recv result of b"" that is ignored. It leaks one file descriptor per connection.
Stuck in FIN_WAIT_2
The active closer waits for a FIN that the peer never sends, for example because the peer application is hung. Linux limits this for fully closed sockets with tcp_fin_timeout (60 seconds by default). A half-closed socket that the application still holds is not timed out.
Silent peer disappearance
If the peer machine crashes or the network path disappears, no FIN or RST arrives. An idle connection stays ESTABLISHED indefinitely. Use application-level heartbeats or TCP keepalive (SO_KEEPALIVE) to detect this.
Inspecting states
On Linux, ss lists sockets by state.
ss -tan state time-wait
ss -tan state close-wait
ss -tan | awk 'NR>1 {count[$1]++} END {for (s in count) print s, count[s]}'The last command counts sockets per state. A growing CLOSE-WAIT count points to an application bug. A large TIME-WAIT count points to churn from short connections.
Exercise
A busy web server shows 20,000 sockets in TIMEWAIT and 3 in CLOSEWAIT. A second server shows 5,000 sockets in CLOSE_WAIT that keep growing. Which server most likely has an application bug, and why?
Show answer
The second server. CLOSEWAIT means the peer sent FIN and the kernel acknowledged it, but the local application has not called close(). A steadily growing count means connections are never being closed, which leaks descriptors. TIMEWAIT on the first server is normal behavior for the side that closes first on many short connections.
Exercise
A client program calls shutdown(SHUT_WR) after sending a request, then calls recv in a loop. Name the segment it sent, the state it entered, and what the server's recv returns once the server has read all request bytes.
Show answer
It sent a FIN and entered FINWAIT1, then FINWAIT2 after the server's ACK. The server's recv returns b"" (end of stream) once it has read all the request bytes. The server can still send its reply, and the client can still read it.
Exercise
Why does the active closer wait in TIME_WAIT for 2 x MSL instead of going straight to CLOSED after sending the final ACK?
Show answer
If the final ACK is lost, the peer retransmits its FIN, and the active closer must still hold the connection state to acknowledge it again. The wait also lets delayed segments from the old connection expire, so they cannot be mistaken for data on a new connection that reuses the same four-tuple.