basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    TCP: handshake, flags, states, windows, and the tcp[13] mask

    TCP delivers bytes in order and retransmits lost packets over best-effort IP: it tracks seq and ack counters, throttles speed with the win window, and keeps connection state. Covers the three-way handshake, RST vs DROP, TIME-WAIT vs CLOSE-WAIT, window scaling, and the tcp[13] flags byte.

    What you’ll get

    Capture the full lifecycle of a short HTTP request in tcpdump -nn: the three-way handshake, data exchange, and connection teardown:

    sudo tcpdump -nn -i eth0 'tcp port 8080'
    # 19:14:30.734148 IP 10.0.10.20.58954 > 10.0.10.10.8080: Flags [S],  seq 1163048860, win 64240, options [mss 1460,sackOK,…,wscale 7], length 0
    # 19:14:30.734172 IP 10.0.10.10.8080 > 10.0.10.20.58954: Flags [S.], seq 2422013359, ack 1163048861, win 65160, options [mss 1460,sackOK,…,wscale 7], length 0
    # 19:14:30.734185 IP 10.0.10.20.58954 > 10.0.10.10.8080: Flags [.],  ack 1, win 502, length 0
    # 19:14:30.734243 IP 10.0.10.20.58954 > 10.0.10.10.8080: Flags [P.], seq 1:79, ack 1, win 502, length 78: HTTP: GET / HTTP/1.1
    # 19:14:30.734250 IP 10.0.10.10.8080 > 10.0.10.20.58954: Flags [.],  ack 79, win 509, length 0
    # 19:14:30.734347 IP 10.0.10.10.8080 > 10.0.10.20.58954: Flags [P.], seq 1:61, ack 79, win 509, length 60: HTTP: HTTP/1.1 200 OK
    # 19:14:30.734357 IP 10.0.10.20.58954 > 10.0.10.10.8080: Flags [.],  ack 61, win 502, length 0
    # 19:14:30.734378 IP 10.0.10.10.8080 > 10.0.10.20.58954: Flags [F.], seq 61, ack 79, win 509, length 0
    # 19:14:30.734428 IP 10.0.10.20.58954 > 10.0.10.10.8080: Flags [F.], seq 79, ack 62, win 502, length 0
    # 19:14:30.734441 IP 10.0.10.10.8080 > 10.0.10.20.58954: Flags [.],  ack 80, win 509, length 0

    The second line — the server’s SYN-ACK reply — contains nearly every parameter that TCP relies on:

    tcpdump -nn -i eth0 'tcp port 8080' · Pick a segment
    In packet 3, the client's win drops from 64240 to 502 because wscale 7 takes effect: 502 × 128 = 64,256 bytes.

    TCP header, seq/ack counters, and the win window

    TCP does not deliver discrete messages — it carries a continuous byte stream sliced into segments no larger than MSS (1460 bytes for IPv4 at MTU 1500, ICMP and MTU).

    • seq (Sequence Number) — the byte offset of the first payload byte in this segment. After the client sends the 78-byte request GET / HTTP/1.1 (seq 1:79), its next byte starts at 79.
    • ack (Acknowledgment Number) — the next byte the receiver expects from the peer. Returning ack 79 says: “every byte up to 78 arrived intact.” If a packet drops in transit, the sender stops seeing ack advance and retransmits the missing segment.
    • win (Window) and wscale — flow control. The base header allocates 16 bits for window size (capping at 65,535 bytes), which is too small for fast links with latency. During the handshake, both sides negotiate wscale (RFC 7323, net.ipv4.tcp_window_scaling = 1), multiplying all subsequent win values by 2^wscale. In the capture above, wscale 7 gives a multiplier of 128, so win 509 represents an effective buffer of 509 × 128 = 65,152 bytes.
    TCP header · 20 bytes (+ options in SYN) · flags byte tcp[13]Pick a layer
    IPv4 header (L3)End to end
    Protocol · 1 B6 (TCP)Tells the kernel to hand the payload to the TCP handler
    Src / Dst IP · 8 B10.0.10.10 > 10.0.10.20Combined with ports to form the connection 5-tuple
    TCP header (L4) and flags byte tcp[13]Seen by sender and receiver

    Flags live in the 14th byte of the TCP header — zero-based offset 13 (tcp[13] in tcpdump BPF filters).

    Src / Dst Port · 4 B8080 > 58954Service port and client ephemeral port
    Seq / Ack · 8 Bseq 1 · ack 79Byte counters for stream reassembly and retransmission
    Flags · tcp[13]0x12 · [S.]ACK bit (16) + SYN bit (2) = 18 (0x12)
    Window · 2 Bwin 509 × 2^7Free space in the receiver buffer
    Flags byte tcp[13] · 00010010 = 16 (ACK) + 2 (SYN) = 0x12
    CWR0128
    ECE064
    URG032
    ACK116
    PSH08
    RST04
    SYN12
    FIN01
    Segment payloadRead by application
    Byte streamHTTP/1.1 200 OK…TCP has no concept of HTTP message boundaries — it delivers ordered bytes

    TCP flags and the tcp[13] bitmask

    Every TCP packet carries a combination of flags in tcp[13]. tcpdump prints them inside brackets (Flags […]):

    Flag In tcpdump Weight (hex) Meaning
    SYN S 2 (0x02) Request to open a connection, synchronize initial seq
    ACK . 16 (0x10) ack field is valid — acknowledges received bytes (set on almost every packet after the first SYN)
    PSH P 8 (0x08) Flush buffered data to the application immediately instead of waiting for a full buffer
    FIN F 1 (0x01) Graceful close of one half of the connection (“no more data from this side”)
    RST R 4 (0x04) Immediate abort: closed port, crashed process, or firewall REJECT

    In tcpdump, you can isolate specific packets — such as bare SYN, SYN-ACK, or any RST — using a bitmask on tcp[13]. Exact match == requires only the selected bits (tcp[13] == 0x12 matches SYN+ACK exclusively), while & != 0 triggers when at least one target bit is set (tcp[13] & 4 != 0 catches any RST, whether [R] or [R.]):

    Byte: 00010010Hex: 0x12Dec: 18Exactly these flags: ACK + SYN (all other bits = 0)
    sudo tcpdump -nn 'tcp[13] == 0x12'
    # by name: sudo tcpdump -nn 'tcp[tcpflags] == (tcp-ack|tcp-syn)'

    Testing the filter on live traffic — only SYN-ACK and RST-ACK show up, skipping thousands of data packets:

    sudo tcpdump -nn -i eth0 'tcp[13] == 0x12 or tcp[13] & 4 != 0'
    # 19:14:31.479205 IP 10.0.10.10.8080 > 10.0.10.20.58962: Flags [S.], seq 2553686243, ack 2005566322, win 65160, …
    # 19:14:31.490140 IP 10.0.10.10.9999 > 10.0.10.20.48500: Flags [R.], seq 0, ack 3815482293, win 0, length 0

    Handshake, RST, and DROP: three patterns in tcpdump

    The first few packets in a capture immediately show where a connection gets stuck:

    1. Client✓ SYN -> ACK -> GET
    2. Server :8080✓ SYN-ACK -> 200 OK
    3. Teardown✓ FIN-ACK both ways
    4. Result✓ TIME-WAIT on server
    19:14:30.734148 IP 10.0.10.20.58954 > 10.0.10.10.8080: Flags [S], seq 1163048860, win 64240, length 0
    19:14:30.734172 IP 10.0.10.10.8080 > 10.0.10.20.58954: Flags [S.], seq 2422013359, ack 1163048861, win 65160, length 0
    19:14:30.734185 IP 10.0.10.20.58954 > 10.0.10.10.8080: Flags [.], ack 1, win 502, length 0
    What happened

    Three packets established the connection, both peers negotiated mss and wscale, exchanged HTTP, and closed cleanly with FIN.

    Check with

    ss -tnp and sudo tcpdump -nn 'tcp port 8080'

    1. Client✓ SYN to :9999
    2. Server kernel✕ nothing listening
    3. Reply✕ Flags [R.] instantly
    4. curl (exit 7)✕ Connection refused
    19:14:30.755324 IP 10.0.10.20.48498 > 10.0.10.10.9999: Flags [S], seq 1434612965, win 64240, length 0
    19:14:30.755343 IP 10.0.10.10.9999 > 10.0.10.20.48498: Flags [R.], seq 0, ack 1434612966, win 0, length 0
    Cause

    The packet reached the host, but no LISTEN socket exists on 10.0.10.10:9999 (or a firewall REJECT rule fired).

    Check with

    sudo ss -tulnp 'sport = :9999' on the server

    1. Client✓ SYN to :8081
    2. nftables (drop)✕ packet silently dropped
    3. Retries✕ same seq after 1 s, 2 s…
    4. curl (exit 28)✕ Connection timed out
    19:14:32.119491 IP 10.0.10.20.51654 > 10.0.10.10.8081: Flags [S], seq 1131254975, win 64240, length 0
    19:14:33.122316 IP 10.0.10.20.51654 > 10.0.10.10.8081: Flags [S], seq 1131254975, win 64240, length 0
    19:14:34.146328 IP 10.0.10.20.51654 > 10.0.10.10.8081: Flags [S], seq 1131254975, win 64240, length 0
    Cause

    No reply arrives at all: the client retransmits SYN with the same seq at increasing intervals (tcp_syn_retries = 6) until it times out.

    Check with

    sudo nft list ruleset and the return route (ip route get)

    TCP states in ss: why TIME-WAIT vs CLOSE-WAIT matters

    Every TCP socket has a state. In day-to-day debugging, five states come up most often:

    State in ss What is happening Sign of trouble
    LISTEN Socket waiting for incoming SYN Normal for a server
    SYN-RECV SYN arrived, server sent SYN-ACK and waits for final ACK Hundreds of rows point to a missing return route or SYN flood
    ESTAB Connection is open and transferring data Normal
    TIME-WAIT Local side closed first (FIN sent and acknowledged); waiting 60 s Usually normal (protects against late packets)
    CLOSE-WAIT Peer sent FIN, kernel acknowledged it, but local program has not called close() Almost always an application bug or socket leak

    The core difference between the last two:

    • TIME-WAIT belongs to the kernel, not the process. In the capture above, the HTTP server initiated teardown (Flags [F.] from 10.0.10.10:8080), so TIME-WAIT appears on the server side with an empty Process column — the program already closed its socket:

      ss -tan state time-wait
      # Recv-Q Send-Q Local Address:Port Peer Address:Port Process
      # 0      0         10.0.10.10:8080   10.0.10.20:58954
    • CLOSE-WAIT is held by a live process. When the client closes a connection and the server forgets to call close(), the socket stays stuck in CLOSE-WAIT with Recv-Q = 1 (one unread FIN queued) and stays tied to that PID until the process exits:

      sudo ss -tnp state close-wait
      # Recv-Q Send-Q Local Address:Port Peer Address:Port Process
      # 1      0         10.0.10.10:8080   10.0.10.20:40786 users:(("python3",pid=6687,fd=7))

      As those sockets accumulate, the process hits its open-file limit (EMFILE: Too many open files) and stops accepting new connections. Fix this in the application code or config, not in kernel tunables.

    During the handshake, both peers negotiate `wscale 7`, and later packets in `tcpdump` show `win 502`. How many bytes is the receiver ready to accept?
    19:14:30.734148 ... Flags [S], win 64240, options [mss 1460,...,wscale 7]
    19:14:30.734185 ... Flags [.], ack 1, win 502, length 0
    During the handshake, both peers negotiate `wscale 7`, and later packets in `tcpdump` show `win 502`. How many bytes is the receiver ready to accept?
    Answer:
    502 × 2^7 = 502 × 128 = 64,256 bytes

    wscale is a power of two (left bit shift), not a direct multiplier. If you start capturing after the handshake, tcpdump misses wscale and prints raw 502 — that does not mean the window is tiny.

    `ss -tan` on a server shows 400 sockets in `CLOSE-WAIT`, all owned by `api-worker`. Where should you look first?
    sudo ss -tnp state close-wait | head -n 3
    # 1 0 10.0.10.10:8080 10.0.10.20:40786 users:(("api-worker",pid=6687,fd=7))
    `ss -tan` on a server shows 400 sockets in `CLOSE-WAIT`, all owned by `api-worker`. Where should you look first?
    Answer:
    CLOSE-WAIT is held by the application until it calls close()

    In CLOSE-WAIT, the network has done its job — the client's FIN arrived and was acknowledged. The kernel will not close a socket owned by a running process, so tcp_fin_timeout has no effect.

    If it doesn’t work

    curl or nc fails immediately with Connection refused in under a millisecond

    Cause
    The SYN packet reached the server, but nothing listens on that port (or the firewall uses REJECT), so the kernel replied with RST (Flags [R.]).
    Fix
    Run sudo ss -tulnp on the server to verify the service is running and listening on the expected interface rather than 127.0.0.1 (Ports and sockets).

    A connection hangs for 10–60 seconds and fails with Connection timed out

    Cause
    A firewall silently drops SYN packets (DROP), or return packets are lost along the path. The client retries SYN (net.ipv4.tcp_syn_retries = 6) with exponential backoff and gives up.
    Fix
    Run tcpdump -nn 'tcp[13] == 0x02 or tcp[13] == 0x12' to check whether SYN leaves and SYN-ACK returns. On the server, inspect nftables rules (input and forward).

    ss -tan on the server piles up hundreds or thousands of CLOSE-WAIT sockets, then the app crashes with Too many open files

    Cause
    Socket leak in application code: the remote client already sent FIN and closed its side, but the server process never called close() and still holds the file descriptor.
    Fix
    Find the leaking process with sudo ss -tnp state close-wait. Restarting clears the sockets temporarily; for a permanent fix, close connections properly in the app code (timeouts, finally/with).

    After a load test or on a reverse proxy, ss -tan shows thousands of lines in TIME-WAIT

    Cause
    Normal TCP behavior: the side that sends FIN first holds the address/port pair for 60 seconds (2×MSL) so late packets from the old session cannot land in a new connection.
    Fix
    TIME-WAIT by itself is not a leak. It only hurts if you exhaust outbound ephemeral ports (about 28,000 per destination IP:port): enable HTTP keep-alive and connection pooling instead of breaking the TCP stack.

    Data transfer stalls abruptly and win 0 (ZeroWindow) shows up in tcpdump

    Cause
    The receiver's buffer is full: the application is not reading data from the socket fast enough (for instance, a stuck handler or blocked disk), so TCP pauses the sender.
    Fix
    Inspect Recv-Q and Send-Q in ss -tnp: a persistently high Recv-Q points to a slow receiving application rather than packet loss on the network.

    Also in this chapter