Closing
FIN, RST, TIME_WAIT and address already in use.
Three packets opened it. Closing takes four, and leaves something behind.
The polite close
A [F.] each way, then a final ACK:
cap "-i lo -n -c 8 tcp port 9000" "echo hi | nc -w 1 127.0.0.1 9000" | tail -3ack 5 covers four bytes plus the FIN. Six bytes gives ack 8:
cap "-i lo -n -c 8 tcp port 9000" "printf 'abcdef' | nc -w 1 127.0.0.1 9000" \
| tail -3The FIN takes a sequence number of its own, so the count is one more than you sent.
Four in the general case — FIN, ACK, FIN, ACK. Here the server combines its ACK and FIN.
Who closes first
Either side can, and each direction closes independently. nc -N closes the write side
when its input ends:
cap "-i lo -n -c 6 tcp port 9000" "printf hi | nc -w 1 -N 127.0.0.1 9000" \
| grep -E 'F\.|P\.'A half-closed connection — one side done, the other still talking — is legal.
RST
The abrupt close — no agreement, no final ACK:
cap "-i lo -n -c 2 port 9999" "nc -w 1 127.0.0.1 9999"That is chapter 3’s refusal. The same [R.] appears when a process dies mid-connection.
TIME_WAIT
The side that closed first keeps the socket for a couple of minutes:
ss -tan state time-wait 'sport = :9700'The connection is finished and the entry remains, so a late packet cannot be taken for part of a new one.
Address already in use
A socket cannot bind a port that still has a TIME_WAIT entry:
python3 -c '
import socket
t = socket.socket()
try:
t.bind(("127.0.0.1", 9700))
except OSError as e:
print("plain:", e)'SO_REUSEADDR
One option says a TIME_WAIT entry is not a conflict:
python3 -c '
import socket
for name, opt in (("plain", 0), ("SO_REUSEADDR", 1)):
t = socket.socket()
if opt: t.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
t.bind(("127.0.0.1", 9700)); print(name + ": ok"); t.close()
except OSError as e:
print(name + ":", e)'Every socket tutorial sets it without saying why. This is why.
It does not let two live listeners share a port; that is SO_REUSEPORT, a different option
entirely.