TCP connection lifecycle
Trace the three-way handshake, data transfer and teardown in a packet capture.
By Invicly Tech, , in Computer Networking. About 13 minutes to read.
In short
TCP provides a reliable, ordered byte stream over unreliable IP. Before sending data, the two sides perform a three-way handshake to agree on initial sequence numbers. Connections end with a FIN exchange in each direction, or abruptly with a RST.
Explained simply
TCP works a bit like a phone call. Before talking, you dial, the other side picks up, and you both confirm you can hear each other. In TCP this takes three packets: SYN ("I want to connect"), SYN-ACK ("OK, I hear you, do you hear me?") and ACK ("Yes"). Only then does data flow. This costs one round trip, the time for a packet to go there and back.
TCP gives every byte a number, called a sequence number. Each side picks a random starting number during the handshake. The receiver answers with an acknowledgement number: the number of the next byte it expects. So both sides always know exactly which bytes have arrived.
Closing is polite too. Each side sends a FIN (finish) when it has nothing more to send, and the other side acknowledges it. Because each direction closes on its own, a normal close takes four packets, often squeezed into three. A RST (reset) is the rude version: it ends the connection at once, like hanging up mid-sentence.
Each end keeps a state for the connection, such as LISTEN, ESTABLISHED or TIME_WAIT, and ss shows them. States are great clues. Thousands of sockets in CLOSE_WAIT mean an app forgets to close connections. Many in SYN-SENT mean a server is not answering.
Press Play on a diagram to walk through it one step at a time.
- Client to Server: SYN seq=x1SYN seq=x
- Server to Client: SYN-ACK seq=y ack=x+12SYN-ACK seq=y ack=x+1
- Client to Server: ACK ack=y+1 (connection established)3ACK ack=y+1 (connection established)
- Client to Server: Data and ACKs flow both ways4Data and ACKs flow both ways
- Client to Server: FIN5FIN
- Server to Client: ACK, then its own FIN6ACK, then its own FIN
- Client to Server: Final ACK; client enters TIME_WAIT7Final ACK; client enters TIME_WAIT
- 1CLOSED
No connection yet
- 2SYN-SENT
SYN sent, waiting for SYN-ACK
- 3ESTABLISHED
Handshake done, data flows
- 4FIN-WAIT-1
Own FIN sent
- 5FIN-WAIT-2
FIN acked, waiting for peer's FIN
- 6TIME-WAIT
Peer's FIN acked, wait 60 s on Linux
- 7CLOSED
Port and 5-tuple free again
- Delivers all queued data first
- Closes one direction at a time
- Acknowledged by the peer
- Active closer enters TIME_WAIT
- Throws away queued data
- Ends both directions at once
- Never acknowledged
- No TIME_WAIT
- App sees refused or reset errors
In depth
The TCP header, field by field
The TCP header is 20 bytes without options and at most 60 bytes with them. It has no length field for the data; the receiver works that out from the IP header.
Source and destination ports take 16 bits each. The sequence number (32 bits) is the number of the first data byte in this segment. The acknowledgement number (32 bits) is the next byte the sender expects to receive, and it is only valid when the ACK flag is set. Data offset (4 bits) gives the header length in 32-bit words, from 5 (20 bytes) to 15 (60 bytes). After 4 reserved bits come 8 flag bits: CWR, ECE, URG, ACK, PSH, RST, SYN and FIN. The window (16 bits) is the free receive buffer space. Then come the checksum, the urgent pointer and up to 40 bytes of options.
- 1Source port (16) | Destination port (16)
Which programs on each end
- 2Sequence number (32)
Number of the first byte in this segment
- 3Acknowledgement number (32)
Next byte expected from the other side
- 4Offset (4) | Reserved (4) | Flags (8) | Window (16)
Flags: CWR ECE URG ACK PSH RST SYN FIN
- 5Checksum (16) | Urgent pointer (16)
Error check over header and data
- 6Options (0-40 bytes)
MSS, window scale, SACK, timestamps
Sequence numbers and what the handshake agrees on
Each side picks a random initial sequence number (ISN). Randomness makes it hard for an attacker to guess numbers and inject fake packets. SYN and FIN each use up one sequence number even though they carry no data, which is why the reply to SYN seq=x is ack=x+1.
After the handshake, numbers simply count bytes. If the client's ISN is 1000 and it sends 200 bytes, those bytes are numbered 1001 to 1200 and the server answers ack=1201. Wireshark and tcpdump show relative numbers (starting at 0 or 1) by default to make this easier to read.
The SYN packets also carry options that can only be agreed at this moment: the maximum segment size (MSS, typically 1460 bytes on IPv4 Ethernet and 1440 on IPv6), window scaling, SACK permitted and timestamps. If one side leaves an option out, the connection runs without it.
- SYN and FIN each consume one sequence number
- ACK number = last byte received + 1
- MSS 1460 = 1500 MTU - 20 IP - 20 TCP
Graceful close, half-close and RST
A FIN means "I will send no more data", not "go away". The other side can keep sending until it sends its own FIN. This is called a half-close, and a program can do it on purpose with shutdown(SHUT_WR), for example to tell a server that the upload is finished while still reading the reply.
A RST ends both directions immediately and is never acknowledged. The kernel sends one when a packet arrives for a port with no socket, when a program aborts a connection (closing with SO_LINGER set to 0), or when a program closes a socket while unread data is still in its receive buffer. The program on the other side sees "Connection refused" (ECONNREFUSED) if the RST answered its SYN, or "Connection reset by peer" (ECONNRESET) on an open connection. Firewalls and load balancers also send RSTs when they drop idle connections.
- Client (closes first) to Server: FIN: client enters FIN_WAIT_11FIN: client enters FIN_WAIT_1
- Server to Client (closes first): ACK: server in CLOSE_WAIT, client in FIN_WAIT_22ACK: server in CLOSE_WAIT, client in FIN_WAIT_2
- Server to Client (closes first): Server may still send its last data3Server may still send its last data
- Server to Client (closes first): FIN: server enters LAST_ACK4FIN: server enters LAST_ACK
- Client (closes first) to Server: ACK: client in TIME_WAIT, server CLOSED5ACK: client in TIME_WAIT, server CLOSED
The 11 TCP states and what piles of them mean
RFC 9293 defines 11 states: CLOSED, LISTEN, SYN-SENT, SYN-RECEIVED, ESTABLISHED, FIN-WAIT-1, FIN-WAIT-2, CLOSE-WAIT, CLOSING, LAST-ACK and TIME-WAIT. ss prints them with short names such as SYN-RECV and ESTAB. The side that closes first (the active closer) goes through FIN-WAIT-1, FIN-WAIT-2 and TIME-WAIT. The other side (the passive closer) goes through CLOSE-WAIT and LAST-ACK. CLOSING only appears when both sides send FIN at the same moment.
One socket in a state tells you little. Hundreds in the same state point straight at a problem.
A client that gets no answer to its SYN retries with growing gaps. With Linux defaults (net.ipv4.tcp_syn_retries = 6, first retry after 1 second, then doubling) connect() gives up after about 127 seconds.
- Many SYN-SENT: remote host down or a firewall drops your SYNs
- Many SYN-RECV on a server: a SYN flood, or clients' final ACKs are lost
- Many CLOSE-WAIT: your app does not call close() after the peer closed
- Many TIME-WAIT: normal on the side that closes lots of short connections
- Stuck FIN-WAIT-2: the peer never closes; Linux frees orphans after tcp_fin_timeout (60 s)
TIME_WAIT: why it exists and how to live with it
The active closer waits in TIME_WAIT for two reasons. First, its final ACK might be lost; the peer would then resend its FIN, and someone must still be there to ACK it again. Second, old delayed packets from this connection must die out before a new connection with the same 5-tuple starts, or they could be mistaken for new data.
The RFC asks for 2 x MSL (maximum segment lifetime). Linux uses a fixed 60 seconds, and no sysctl changes it. A common mix-up: net.ipv4.tcp_fin_timeout controls orphaned FIN-WAIT-2 sockets, not TIME_WAIT.
TIME_WAIT sockets use very little memory. The only real cost is the port they hold on a client making many short connections to one destination. Fix that with keep-alive or connection pools. net.ipv4.tcp_tw_reuse lets new outgoing connections reuse TIME_WAIT ports safely using timestamps. Never follow old advice to enable tcp_tw_recycle: it broke clients behind NAT and was removed in Linux 4.12.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Trace SYN, SYN-ACK, ACK~45m
- 2Follow sequence and acknowledgement numbers~45m
- 3Trace FIN and RST teardown~45m
- 4Explain TIME_WAIT and connection states~45m
Key points
- The handshake costs one round trip before data can flow.
- Sequence numbers count bytes, not packets.
- RST means the port is closed or the connection was aborted.
- TIME_WAIT lasts about twice the maximum segment lifetime to absorb late packets.
Key terms
Tap a card to flip it. 0/5 known
Examples
sudo tcpdump -i any -nn 'tcp port 443 and (tcp[tcpflags] & (tcp-syn|tcp-fin|tcp-rst) != 0)'
curl -s https://example.com > /dev/null
ss -tan state time-wait | headReading a handshake in tcpdump
Capture traffic to one server and read the flags. Flags [S] is the SYN, with the client's ISN and its options: MSS 1460, SACK allowed, timestamps and window scale 7. [S.] is the SYN-ACK (the dot means ACK); its ack is the client's ISN plus 1. [.] is the plain ACK that completes the handshake. tcpdump now switches to relative numbers, so ack 1 means "I got your SYN". [P.] carries 517 bytes of data (here a TLS ClientHello) as bytes 1 to 517, and the server answers ack 518. Add -S to see absolute numbers throughout.
$ sudo tcpdump -i any -nn 'host 198.51.100.5 and tcp port 443'
IP 192.0.2.10.51544 > 198.51.100.5.443: Flags [S], seq 3127519830, win 64240, options [mss 1460,sackOK,TS val 1 ecr 0,nop,wscale 7], length 0
IP 198.51.100.5.443 > 192.0.2.10.51544: Flags [S.], seq 801443172, ack 3127519831, win 65160, options [mss 1460,sackOK,TS val 9 ecr 1,nop,wscale 7], length 0
IP 192.0.2.10.51544 > 198.51.100.5.443: Flags [.], ack 1, win 502, length 0
IP 192.0.2.10.51544 > 198.51.100.5.443: Flags [P.], seq 1:518, ack 1, win 502, length 517
IP 198.51.100.5.443 > 192.0.2.10.51544: Flags [.], ack 518, win 507, length 0Hunting a CLOSE_WAIT leak
An API server slowly gets worse and finally logs "Too many open files". Step 1: count sockets per state; CLOSE-WAIT is far ahead of the rest. Step 2: find the process that owns them. CLOSE_WAIT means the peer already sent FIN and the kernel acknowledged it, but your program never called close(), so the socket and its file descriptor live forever. Step 3: count that process's open file descriptors to confirm. The fix is in the code: close response bodies and connections in a finally block or a with statement, or use a connection pool.
ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c | sort -rn
# 3012 CLOSE-WAIT
# 140 ESTAB
sudo ss -tanp state close-wait | head -3
sudo ls /proc/$(pgrep -of myapp)/fd | wc -lQuick reference
- Handshake: SYN, SYN-ACK, ACK; SYN and FIN each consume one sequence number
- tcpdump flags: [S] SYN, [S.] SYN-ACK, [.] ACK, [P.] data with PSH, [F.] FIN, [R] reset
- TCP header: 20 bytes minimum, 60 maximum; data offset counts 32-bit words (5 to 15)
- Count sockets per state: ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c
- Many CLOSE-WAIT = your app is not closing sockets; many SYN-SENT = the peer is not answering
- Linux TIME_WAIT is a fixed 60 s; tcp_fin_timeout is for orphaned FIN-WAIT-2, not TIME_WAIT
- Connection refused = a RST answered your SYN; a timeout usually means a firewall dropped it
- Wireshark: tcp.flags.syn == 1 && tcp.flags.ack == 0 shows only new connection attempts
Common mistakes
- Reading a RST as a network failure; often the port is simply closed.
- Assuming one send equals one received message; TCP is a byte stream.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Capture your own handshake and teardown while running curl against an HTTP site. Point out the SYN, SYN-ACK, ACK and the FIN packets, and the MSS each side offered.
- Exercise 2medium
Make a TIME_WAIT socket appear on your own machine and work out which side holds it and why.
- Exercise 3hard
Produce two kinds of RST on loopback and capture both: one from a closed port, and one from a program that aborts a connection with SO_LINGER set to 0.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why is it called a three-way handshake?
- Three packets are needed so that each side sends its own starting sequence number and gets it acknowledged. The server's SYN and its ACK of the client's SYN travel together in one packet, so two SYNs and two ACKs fit into three packets.
- What is the difference between Connection refused and Connection timed out?
- Refused means the host is reachable and answered your SYN with a RST, usually because no program listens on that port. Timed out means no answer came at all, often because a firewall silently drops the packets or the host is down.
- Are thousands of TIME_WAIT sockets a problem?
- Usually not. They are cheap and clear themselves after 60 seconds on Linux. They only hurt when a client runs out of ephemeral ports to one destination, and reusing connections fixes that.
- Why does Wireshark show sequence numbers starting at 0?
- Wireshark shows relative sequence numbers by default, counting from the ISN, so they are easy to read. The real numbers are random 32-bit values; you can see them as the raw sequence number field in the packet details.