Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Computer Basics / Networking 2: TCP, UDP and Ports

    Closing and Connection States

    FIN ("finish") — the polite close: "I have no more data to send." Each direction closes separately,

    Chapter 8 of 123 min read

    The Plain Picture#

    Ending a phone call politely: "I'm done talking." — "OK, I'm done too." — "Bye." — "Bye." Or rudely: just slam the phone down.

    The Real Names#

    • FIN ("finish") — the polite close: "I have no more data to send." Each direction closes separately, so a normal close takes four packets: FIN, ACK, FIN, ACK.

    • RST ("reset") — the rude close: "this connection is dead, now." Sent when a packet arrives for a connection that doesn't exist (a port with nothing listening, Ch 5), or when a program closes abruptly. Your program sees it as "connection reset by peer".

    Under the Hood — the states you'll see in real tools#

    Tools like netstat -an (Mac/Linux) or ss -tan (Linux) show each connection's state:

    StateMeaningWhen you should worry
    LISTENa server socket waiting for connections—
    ESTABLISHEDan open, working connectionthousands more than expected = connection leak
    TIME_WAITthis side closed first; waiting a while before fully forgetting the connectiontens of thousands = opening and closing too many connections (Ch 12)
    CLOSE_WAITthe other side closed; our program hasn't closed its socket yetgrowing numbers = a bug in our code — we forget to close connections

    Why TIME_WAIT exists: after closing, the side that closed first waits (60 seconds on Linux) so any delayed packets from the old connection die out and don't confuse a new connection with the same five-tuple (Ch 1). It's normal, but huge numbers of them can use up the ephemeral ports (Ch 1).

    Keep-alive: an idle TCP connection sends nothing at all, so a dead peer might not be noticed for hours. TCP keep-alive probes send tiny packets after a period of silence to check the other side is still there. Cloud load balancers and NAT devices (Ch 10) also silently drop connections idle longer than their timeout (often 350 seconds on AWS NAT gateways) — a common cause of mysterious "connection reset" errors in long-lived database connections.

    Check yourself

    3 questions
    1

    What's the difference between FIN and RST?

    Show answer

    FIN is a polite "I'm done sending"; RST abruptly kills the connection.

    2

    Your server shows 5,000 connections in CLOSE_WAIT. Whose bug is it?

    Show answer

    Yours — the peer closed, and your program never closed its side of the sockets.

    3

    Why does TIME_WAIT exist?

    Show answer

    So delayed packets from an old connection can't be mistaken for part of a new connection with the same five-tuple.