Chapter 28 of 48

TCP Header & TCP State Diagram

In the previous chapter you saw the three-way handshake, sequence numbers, the receive window and the FIN/ACK close. But where do all these values actually live? And how does TCP know whether a connection is still opening, fully open, or half-closed?

The answers are the TCP header and the TCP state diagram.

TCP Header → The control information placed in front of every TCP segment (ports, sequence number, ACK number, flags, window, checksum and more).

TCP State Diagram → The set of states a TCP connection moves through, from CLOSED to ESTABLISHED and back to CLOSED, and the events that cause each move.

Both are favourite topics in GATE, university exams and networking interviews. Let's take them one at a time.


What Is a TCP Segment?

The unit of data that TCP sends is called a segment. A segment has two parts: a header and the data (payload) coming from the application. The segment is then carried inside an IP packet.

+-------------+--------------+------------------------+
|  IP header  |  TCP header  |  Application data      |
|  (20+ B)    |  (20-60 B)   |  (e.g. part of a file) |
+-------------+--------------+------------------------+
              |<------------ TCP segment ------------>|
|<------------------- IP packet --------------------->|

The header is what lets TCP provide reliability, ordering, flow control and connection management. Without it, the receiver would just see raw bytes with no idea where they belong.


TCP Header Format

The TCP header is drawn in rows of 32 bits (4 bytes). The fixed part is 5 rows = 20 bytes. After it come optional options of up to 40 bytes, so the header is 20 to 60 bytes long.

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-------------------------------+-------------------------------+
|          Source Port          |       Destination Port        |
+-------------------------------+-------------------------------+
|                        Sequence Number                        |
+---------------------------------------------------------------+
|                     Acknowledgment Number                     |
+-------+-------+-+-+-+-+-+-+-+-+-------------------------------+
| Data  |       |C|E|U|A|P|R|S|F|                               |
|Offset | Rsrvd |W|C|R|C|S|S|Y|I|            Window             |
|       |       |R|E|G|K|H|T|N|N|                               |
+-------+-------+-+-+-+-+-+-+-+-+-------------------------------+
|           Checksum            |        Urgent Pointer         |
+-------------------------------+-------------------------------+
|                    Options (0 to 40 bytes)                    |
+---------------------------------------------------------------+
|                             Data                              |
+---------------------------------------------------------------+

This is the layout used by the current TCP standard, RFC 9293 (2022), which replaced the original RFC 793 from 1981.


TCP Header Fields One by One

Field

Size

What It Does

Source Port

16 bits

Port of the sending application (0 to 65535)

Destination Port

16 bits

Port of the receiving application, for example 443 for HTTPS

Sequence Number

32 bits

Number of the first data byte in this segment. In a SYN segment, it carries the Initial Sequence Number (ISN)

Acknowledgment Number

32 bits

The next byte the sender expects to receive. Valid only when the ACK flag is set

Data Offset (Header Length)

4 bits

Header length in 32-bit words. Minimum 5 (20 bytes), maximum 15 (60 bytes)

Reserved

4 bits

Not used, must be zero

Flags (Control bits)

8 bits

CWR, ECE, URG, ACK, PSH, RST, SYN, FIN

Window

16 bits

Receive window: how many more bytes the sender of this segment is ready to accept (flow control)

Checksum

16 bits

Error check over a pseudo-header, the TCP header and the data

Urgent Pointer

16 bits

Used only when URG is set; marks the end of urgent data

Options

0 to 40 bytes

Extra features such as MSS, window scaling, SACK and timestamps; padded to a multiple of 4 bytes

Notice what is not in the TCP header: there are no IP addresses. Those are in the IP header. A connection is identified by the 4-tuple (source IP, source port, destination IP, destination port), which is built using both headers.

There is also no length field for the whole segment. TCP works out the data length as IP total length − IP header length − TCP header length.


TCP Flags (Control Bits)

Each flag is a single bit. A segment can have several flags set at once, for example SYN + ACK.

Flag

Name

Meaning

SYN

Synchronize

Starts a connection and carries the initial sequence number

ACK

Acknowledgment

The Acknowledgment Number field is valid. Set on every segment after the first SYN

FIN

Finish

"I have no more data to send" (closes one direction)

RST

Reset

Abort the connection immediately, or refuse a connection to a closed port

PSH

Push

Ask the receiver to pass the data to the application without waiting to fill a buffer

URG

Urgent

The Urgent Pointer field is valid. Rarely used today, and new applications are advised not to use it

ECE

ECN-Echo

Used with Explicit Congestion Notification (ECN) to tell the sender that the network marked congestion

CWR

Congestion Window Reduced

The sender's reply to ECE: "I have reduced my sending rate"

Exam note: many textbooks show the original RFC 793 layout with 6 flags (URG, ACK, PSH, RST, SYN, FIN) and 6 reserved bits. Later, ECN (RFC 3168) took two of the reserved bits for CWR and ECE. If a question asks for "the six TCP flags", list the original six; mentioning CWR and ECE shows extra depth.

Two rules worth remembering:

  • SYN and FIN each consume one sequence number, even though they carry no data. That is why the reply to a SYN with seq = x has ack = x + 1.

  • A pure ACK (no data, no SYN, no FIN) does not consume a sequence number.


Data Offset: Finding the Header Length

The Data Offset field counts 4-byte words, not bytes. This is a very common exam trap.

Header length (bytes) = Data Offset x 4

Data Offset = 5   ->  5 x 4 = 20 bytes  (no options)
Data Offset = 8   ->  8 x 4 = 32 bytes  (12 bytes of options)
Data Offset = 15  -> 15 x 4 = 60 bytes  (40 bytes of options, the maximum)

Worked example: byte 12 of a captured TCP header is 0x80. What is the header length?

The Data Offset is the upper 4 bits of byte 12: 0x80 = 1000 0000, so the upper 4 bits are 1000 = 8. Header length = 8 × 4 = 32 bytes, which means 32 − 20 = 12 bytes of options.

Because 4 bits can hold at most 15, the header can never be longer than 15 × 4 = 60 bytes. That is why options are limited to 40 bytes.


TCP Options

Options are mostly exchanged in the SYN and SYN-ACK segments, so both sides agree on extra features at connection start.

Kind

Length (bytes)

Option

Purpose

0

1

End of Option List

Marks the end of the options

1

1

No-Operation (NOP)

Padding, used to align the next option

2

4

Maximum Segment Size (MSS)

Largest amount of data (not counting headers) this side wants to receive in one segment

3

3

Window Scale

Multiplies the 16-bit window by 2shift (shift up to 14)

4

2

SACK Permitted

"I understand Selective Acknowledgments"

5

variable

SACK

Lists blocks of data received out of order, so only the missing pieces are resent

8

10

Timestamps

Better RTT measurement and protection against wrapped sequence numbers (PAWS)

On Ethernet, the typical MSS is 1460 bytes: the 1500-byte MTU minus a 20-byte IPv4 header and a 20-byte TCP header. If no MSS option is sent, an IPv4 sender must assume a default MSS of 536 bytes.


Sequence and Acknowledgment Numbers in Action

Sequence numbers count bytes, not segments. Suppose the client picks ISN = 1000 and the server picks ISN = 5000:

Client                                           Server
  |-- SYN            seq=1000                   -->|
  |<- SYN+ACK        seq=5000  ack=1001         ---|   (SYN used up 1000)
  |-- ACK            seq=1001  ack=5001         -->|
  |-- 500 bytes      seq=1001  (bytes 1001-1500)-->|
  |<- ACK                      ack=1501         ---|
  |-- 300 bytes      seq=1501  (bytes 1501-1800)-->|
  |<- ACK                      ack=1801         ---|
  |-- FIN            seq=1801                   -->|
  |<- ACK                      ack=1802         ---|   (FIN used up 1801)

Two simple formulas cover almost every exam question:

Next sequence number   = current seq + data bytes (+1 if SYN or FIN is set)
Acknowledgment number  = sequence number of the next byte expected

Real systems choose the ISN randomly rather than starting at 0. This makes it hard for an attacker to guess valid sequence numbers and inject fake segments, and it avoids confusion with old segments from an earlier connection.

Sequence Number Wrap-Around

A 32-bit sequence number can count 232 = 4,294,967,296 bytes (4 GiB) before it starts again from 0.

Wrap time = 2^32 bytes / sending rate (bytes per second)

At 10 Mbps  (1.25 MB/s): 4,294,967,296 / 1,250,000     = 3435.97 s (about 57 minutes)
At 1 Gbps   (125 MB/s) : 4,294,967,296 / 125,000,000   = 34.36 s
At 10 Gbps  (1.25 GB/s): 4,294,967,296 / 1,250,000,000 = 3.44 s

The standard assumes an old segment can survive in the network for a Maximum Segment Lifetime (MSL) of 2 minutes. At 1 Gbps the numbers wrap in about 34 seconds, which is shorter than the MSL, so an old delayed segment could be mistaken for a new one. Fast connections use the Timestamps option (PAWS: Protection Against Wrapped Sequences) to tell them apart.


The Window Field and Window Scaling

The 16-bit Window field is the receive window (rwnd) you studied for flow control. Its largest value is 216 − 1 = 65,535 bytes. Since a sender can have at most one window of unacknowledged data per round trip:

Maximum throughput  <=  Window size / RTT

Worked example 1: window = 65,535 bytes, RTT = 100 ms.

Throughput <= 65,535 x 8 bits / 0.1 s = 5,242,800 bits/s  (about 5.24 Mbps)

So without scaling, a 100 ms path can never go faster than about 5.24 Mbps, even on a 1 Gbps link.

Worked example 2: how big must the window be to fill a 1 Gbps link with RTT = 100 ms? The answer is the bandwidth-delay product (BDP):

BDP = bandwidth x RTT = 1,000,000,000 bits/s x 0.1 s = 100,000,000 bits = 12,500,000 bytes

Scale factor needed = 12,500,000 / 65,535 = 190.7  ->  need 2^shift >= 190.7
shift = 7 -> max window = 65,535 x 128 =  8,388,480 bytes  (too small)
shift = 8 -> max window = 65,535 x 256 = 16,776,960 bytes  (enough)

The Window Scale option (RFC 7323) solves this. Each side sends a shift count (0 to 14) in its SYN, and later window values are multiplied by 2shift. The largest possible window is 65,535 × 214 = 1,073,725,440 bytes (about 1 GiB).

Scaling is used only if both sides send the option in their SYN segments, and the Window field inside a SYN segment itself is never scaled.


The TCP Checksum and Pseudo-Header

The checksum lets the receiver detect corrupted segments. It is the 16-bit one's complement of the one's complement sum of all 16-bit words in:

  1. A pseudo-header taken from the IP layer: source IP, destination IP, a zero byte, protocol number (6 for TCP) and TCP length

  2. The TCP header (with the checksum field set to 0 while computing)

  3. The data (padded with a zero byte if its length is odd)

Pseudo-header (IPv4, 12 bytes, never actually transmitted)
+---------------------------------------------------------------+
|                       Source IP Address                       |
+---------------------------------------------------------------+
|                    Destination IP Address                     |
+---------------+---------------+-------------------------------+
|     Zero      | Protocol = 6  |          TCP Length           |
+---------------+---------------+-------------------------------+

Why include IP addresses? So that a segment delivered to the wrong host (for example, because of a corrupted IP address) fails the check. The receiver adds everything up again including the received checksum; if the result is 0 (after the final complement), the segment is accepted. The Error Detection & Correction chapter introduced checksums in general; TCP uses this specific one's complement version, the same kind of checksum used by IPv4 and UDP.

Unlike UDP over IPv4, where the checksum is optional, the TCP checksum is mandatory.


Build and Parse a TCP Header in Python

This program builds a real SYN segment byte by byte (with MSS, Window Scale and SACK-Permitted options), computes the checksum with the pseudo-header, then parses the bytes back. It uses only the standard library and does not send anything on the network.

import socket
import struct

def checksum16(data):
    """16-bit one's complement of the one's complement sum."""
    if len(data) % 2 == 1:
        data += b"\x00"                    # pad to an even length
    total = 0
    for i in range(0, len(data), 2):
        total += (data[i] << 8) | data[i + 1]
        total = (total & 0xFFFF) + (total >> 16)   # wrap the carry around
    return ~total & 0xFFFF

def build_tcp_segment(src_ip, dst_ip, src_port, dst_port, seq, ack,
                      flags, window, options=b"", payload=b""):
    header_len = 20 + len(options)         # options must be a multiple of 4
    data_offset = header_len // 4          # measured in 32-bit words
    offset_byte = data_offset << 4         # upper 4 bits; reserved bits = 0
    header = struct.pack("!HHIIBBHHH", src_port, dst_port, seq, ack,
                         offset_byte, flags, window, 0, 0) + options
    # pseudo-header: src IP, dst IP, zero byte, protocol (6), TCP length
    pseudo = struct.pack("!4s4sBBH", socket.inet_aton(src_ip),
                         socket.inet_aton(dst_ip), 0, 6,
                         len(header) + len(payload))
    csum = checksum16(pseudo + header + payload)
    header = header[:16] + struct.pack("!H", csum) + header[18:]
    return header + payload, pseudo

FLAG_NAMES = ["FIN", "SYN", "RST", "PSH", "ACK", "URG", "ECE", "CWR"]

def parse_tcp_header(seg):
    (sport, dport, seq, ack, off, flags,
     window, csum, urg) = struct.unpack("!HHIIBBHHH", seg[:20])
    data_offset = off >> 4
    names = [FLAG_NAMES[i] for i in range(8) if flags & (1 << i)]
    print("Source port      :", sport)
    print("Destination port :", dport)
    print("Sequence number  :", seq)
    print("Ack number       :", ack)
    print("Data offset      :", data_offset, "words =", data_offset * 4, "bytes")
    print("Flags            :", "+".join(names), "(0x%02x)" % flags)
    print("Window           :", window)
    print("Checksum         : 0x%04x" % csum)
    print("Urgent pointer   :", urg)
    print("Options (hex)    :", seg[20:data_offset * 4].hex(" "))

# MSS=1460 | NOP | Window Scale=7 | NOP | NOP | SACK-Permitted  -> 12 bytes
options = bytes([2, 4, 0x05, 0xB4, 1, 3, 3, 7, 1, 1, 4, 2])
SYN = 0x02
seg, pseudo = build_tcp_segment("192.0.2.10", "203.0.113.5", 50000, 443,
                                seq=1000, ack=0, flags=SYN,
                                window=64240, options=options)

print("Segment (%d bytes):" % len(seg), seg.hex(" "))
parse_tcp_header(seg)
# A receiver re-computes the sum over pseudo-header + segment; 0 means OK
print("Receiver check   :", checksum16(pseudo + seg))

Output:

Segment (32 bytes): c3 50 01 bb 00 00 03 e8 00 00 00 00 80 02 fa f0 ad 1c 00 00 02 04 05 b4 01 03 03 07 01 01 04 02
Source port      : 50000
Destination port : 443
Sequence number  : 1000
Ack number       : 0
Data offset      : 8 words = 32 bytes
Flags            : SYN (0x02)
Window           : 64240
Checksum         : 0xad1c
Urgent pointer   : 0
Options (hex)    : 02 04 05 b4 01 03 03 07 01 01 04 02
Receiver check   : 0

Read the hex dump using the header diagram:

  • c3 50 = 50000 (source port), 01 bb = 443 (destination port)

  • 00 00 03 e8 = 1000 (sequence number), 00 00 00 00 = 0 (ACK number; ACK flag is not set)

  • 80 → Data Offset 8 → 32-byte header; 02 → only SYN is set

  • fa f0 = 64240 (window), ad 1c = checksum, 00 00 = urgent pointer

  • 02 04 05 b4 = MSS 1460, 01 = NOP, 03 03 07 = Window Scale with shift 7, 01 01 = two NOPs, 04 02 = SACK Permitted

The final line shows the receiver's check: summing the pseudo-header and the whole segment (including the checksum) gives 0, so the segment is accepted. Change any single byte of seg and the result will no longer be 0.


TCP Header vs UDP Header

Feature

TCP Header

UDP Header

Size

20 to 60 bytes

Fixed 8 bytes

Ports

Yes

Yes

Sequence / ACK numbers

Yes

No

Flags

Yes (SYN, ACK, FIN, RST, ...)

No

Window (flow control)

Yes

No

Length field

No (only header length)

Yes (header + data)

Checksum

Mandatory

Optional in IPv4, mandatory in IPv6

Options

Yes

No


Why Does TCP Need States?

TCP is connection-oriented, so each endpoint must remember where it is in the life of a connection. For example, a FIN means something different if the connection is fully open than if this side has already sent its own FIN.

The operating system keeps this information in a Transmission Control Block (TCB) for every connection: the 4-tuple, sequence numbers, window sizes, timers, and the current state.

The TCP state diagram is a finite state machine. Each arrow shows: event that happened / segment sent in response. Events are either something the application does (open, close) or a segment that arrives (SYN, ACK, FIN).


The 11 TCP States

State

Meaning

Who Is Usually Here

CLOSED

No connection exists (a starting/ending point, not a real state stored in a TCB)

Both

LISTEN

Waiting for a connection request (SYN)

Server

SYN-SENT

SYN sent, waiting for SYN-ACK

Client

SYN-RECEIVED

SYN received and SYN-ACK sent, waiting for the final ACK

Server

ESTABLISHED

Connection open, data can flow both ways

Both

FIN-WAIT-1

This side sent FIN, waiting for its ACK (or the peer's FIN)

Active closer

FIN-WAIT-2

Our FIN is acknowledged; waiting for the peer's FIN

Active closer

CLOSE-WAIT

Peer sent FIN; waiting for our own application to call close

Passive closer

CLOSING

Both sides sent FIN at the same time; waiting for the ACK of our FIN

Both (simultaneous close)

LAST-ACK

We sent our FIN after receiving the peer's FIN; waiting for the last ACK

Passive closer

TIME-WAIT

Waiting 2 × MSL to be sure the peer got our last ACK and old segments have died out

Active closer

Tools write the names slightly differently, for example SYN_RECV, TIME_WAIT or FIN_WAIT2, but they are the same states.


TCP State Diagram

Here is the state diagram for the normal paths. The left side is the active closer (the side that calls close first) and the right side is the passive closer.

                            +---------+
                            | CLOSED  |
                            +---------+
              passive open    |     |    active open
              (server)        |     |    send SYN (client)
                              v     v
                   +--------+         +----------+
                   | LISTEN |         | SYN-SENT |
                   +--------+         +----------+
        rcv SYN        |                    |   rcv SYN+ACK
        send SYN+ACK   v                    |   send ACK
              +--------------+              |
              | SYN-RECEIVED |              |
              +--------------+              |
        rcv ACK        |                    |
                       v                    v
                   +-------------------------+
                   |       ESTABLISHED       |
                   +-------------------------+
      close            |                    |   rcv FIN
      send FIN         v                    v   send ACK
             +------------+            +------------+
             | FIN-WAIT-1 |            | CLOSE-WAIT |
             +------------+            +------------+
  rcv ACK of FIN |      | rcv FIN           |   close
                 |      | send ACK          v   send FIN
                 v      v              +----------+
      +------------+  +---------+      | LAST-ACK |
      | FIN-WAIT-2 |  | CLOSING |      +----------+
      +------------+  +---------+           |   rcv ACK of FIN
   rcv FIN  |              |  rcv ACK       v
   send ACK |              |  of FIN   +--------+
            v              v           | CLOSED |
         +-------------------+         +--------+
         |     TIME-WAIT     |
         +-------------------+
                   |   wait 2 x MSL
                   v
              +--------+
              | CLOSED |
              +--------+

A few less common transitions are not drawn above:

  • SYN-SENT → SYN-RECEIVED on receiving a SYN (simultaneous open: both sides send SYN at the same time).

  • FIN-WAIT-1 → TIME-WAIT when the peer's FIN and the ACK of our FIN arrive in the same segment.

  • LISTEN → CLOSED and SYN-SENT → CLOSED when the application calls close.

  • SYN-RECEIVED → LISTEN on receiving RST (if the connection came from a passive open).


Walkthrough: Opening a Connection

Client state       Segment                 Server state
CLOSED                                     CLOSED
                                           LISTEN        (socket: listen())
SYN-SENT     ---- SYN ------------------>  (connect())
             <--- SYN+ACK --------------   SYN-RECEIVED
ESTABLISHED  ---- ACK ------------------>
                                           ESTABLISHED

Notice that the client becomes ESTABLISHED one half-RTT earlier than the server: the client is established as soon as it sends the final ACK, while the server must wait for that ACK to arrive.


Walkthrough: Closing a Connection

Because TCP is full-duplex, each direction is closed separately. Suppose the client closes first:

Client state       Segment                 Server state
ESTABLISHED                                ESTABLISHED
FIN-WAIT-1   ---- FIN ------------------>  (client called close())
             <--- ACK ------------------   CLOSE-WAIT
FIN-WAIT-2                                 (server may still send data here)
             <--- FIN ------------------   LAST-ACK  (server called close())
TIME-WAIT    ---- ACK ------------------>
   ...                                     CLOSED
(2 x MSL)
CLOSED

Between CLOSE-WAIT and LAST-ACK, the connection is half-closed: the client has finished sending, but the server can still send data to the client. This is useful when, for example, a client sends a request, signals "I'm done sending", and still waits for the full reply.

Sometimes the server's ACK and FIN are sent together in one segment, which makes the close look like a three-segment exchange (FIN, FIN+ACK, ACK).


TIME-WAIT Explained

TIME-WAIT is the most asked-about state. Only the side that closes first (the active closer) enters it, and it stays there for 2 × MSL.

There are two reasons:

  1. To resend the final ACK if it is lost. If the last ACK is lost, the peer (in LAST-ACK) will retransmit its FIN. A side in TIME-WAIT still remembers the connection and can ACK it again. Without TIME-WAIT it would reply with RST, and the peer would see an error instead of a clean close.

  2. To let old duplicate segments die out. If a new connection with the same 4-tuple started immediately, a delayed segment from the old connection could be accepted as valid data in the new one. Waiting 2 × MSL makes sure any such segment has expired.

Why 2 × MSL and not just MSL? One MSL covers the time for our final ACK to travel to the peer, and one more MSL covers a retransmitted FIN coming back in case that ACK was lost.

The standard takes MSL to be 2 minutes, which gives a 4-minute TIME-WAIT. Real systems often use less; for example, Linux uses a fixed TIME-WAIT of 60 seconds.


Simulate the TCP State Machine in Python

The program below stores the state diagram as a table of (state, event) → (next state, segment to send) and replays two scenarios. It is a model of the rules, not a real network connection.

# (current state, event) -> (next state, segment to send or None)
TRANSITIONS = {
    ("CLOSED",       "passive open"): ("LISTEN",       None),
    ("CLOSED",       "active open"):  ("SYN-SENT",     "SYN"),
    ("LISTEN",       "rcv SYN"):      ("SYN-RECEIVED", "SYN+ACK"),
    ("LISTEN",       "close"):        ("CLOSED",       None),
    ("SYN-SENT",     "rcv SYN+ACK"):  ("ESTABLISHED",  "ACK"),
    ("SYN-SENT",     "rcv SYN"):      ("SYN-RECEIVED", "SYN+ACK"),
    ("SYN-SENT",     "close"):        ("CLOSED",       None),
    ("SYN-RECEIVED", "rcv ACK"):      ("ESTABLISHED",  None),
    ("SYN-RECEIVED", "close"):        ("FIN-WAIT-1",   "FIN"),
    ("ESTABLISHED",  "close"):        ("FIN-WAIT-1",   "FIN"),
    ("ESTABLISHED",  "rcv FIN"):      ("CLOSE-WAIT",   "ACK"),
    ("FIN-WAIT-1",   "rcv ACK"):      ("FIN-WAIT-2",   None),
    ("FIN-WAIT-1",   "rcv FIN"):      ("CLOSING",      "ACK"),
    ("FIN-WAIT-1",   "rcv FIN+ACK"):  ("TIME-WAIT",    "ACK"),
    ("FIN-WAIT-2",   "rcv FIN"):      ("TIME-WAIT",    "ACK"),
    ("CLOSING",      "rcv ACK"):      ("TIME-WAIT",    None),
    ("CLOSE-WAIT",   "close"):        ("LAST-ACK",     "FIN"),
    ("LAST-ACK",     "rcv ACK"):      ("CLOSED",       None),
    ("TIME-WAIT",    "2MSL timeout"): ("CLOSED",       None),
}

class TCPEndpoint:
    def __init__(self, name):
        self.name = name
        self.state = "CLOSED"

    def handle(self, event):
        key = (self.state, event)
        if key not in TRANSITIONS:
            raise ValueError(f"{self.name}: '{event}' not valid in {self.state}")
        new_state, send = TRANSITIONS[key]
        out = f"  send {send}" if send else ""
        line = f"{self.name:<7}{self.state:<13} --{event:<13}--> {new_state:<13}{out}"
        print(line.rstrip())
        self.state = new_state

def run(title, steps):
    print(f"--- {title} ---")
    peers = {"client": TCPEndpoint("client"), "server": TCPEndpoint("server")}
    for who, event in steps:
        peers[who].handle(event)
    print()

run("Open, then client closes first", [
    ("server", "passive open"),
    ("client", "active open"),     # client sends SYN
    ("server", "rcv SYN"),         # server replies SYN+ACK
    ("client", "rcv SYN+ACK"),     # client replies ACK
    ("server", "rcv ACK"),
    ("client", "close"),           # client sends FIN
    ("server", "rcv FIN"),         # server ACKs it
    ("client", "rcv ACK"),
    ("server", "close"),           # server sends its own FIN
    ("client", "rcv FIN"),         # client ACKs it
    ("server", "rcv ACK"),
    ("client", "2MSL timeout"),
])

run("Simultaneous close (both call close at the same time)", [
    ("server", "passive open"), ("client", "active open"),
    ("server", "rcv SYN"), ("client", "rcv SYN+ACK"), ("server", "rcv ACK"),
    ("client", "close"), ("server", "close"),   # FINs cross in the network
    ("client", "rcv FIN"), ("server", "rcv FIN"),
    ("client", "rcv ACK"), ("server", "rcv ACK"),
    ("client", "2MSL timeout"), ("server", "2MSL timeout"),
])

try:
    TCPEndpoint("client").handle("rcv FIN")    # FIN on a closed socket
except ValueError as e:
    print("Error:", e)

Output:

--- Open, then client closes first ---
server CLOSED        --passive open --> LISTEN
client CLOSED        --active open  --> SYN-SENT       send SYN
server LISTEN        --rcv SYN      --> SYN-RECEIVED   send SYN+ACK
client SYN-SENT      --rcv SYN+ACK  --> ESTABLISHED    send ACK
server SYN-RECEIVED  --rcv ACK      --> ESTABLISHED
client ESTABLISHED   --close        --> FIN-WAIT-1     send FIN
server ESTABLISHED   --rcv FIN      --> CLOSE-WAIT     send ACK
client FIN-WAIT-1    --rcv ACK      --> FIN-WAIT-2
server CLOSE-WAIT    --close        --> LAST-ACK       send FIN
client FIN-WAIT-2    --rcv FIN      --> TIME-WAIT      send ACK
server LAST-ACK      --rcv ACK      --> CLOSED
client TIME-WAIT     --2MSL timeout --> CLOSED

--- Simultaneous close (both call close at the same time) ---
server CLOSED        --passive open --> LISTEN
client CLOSED        --active open  --> SYN-SENT       send SYN
server LISTEN        --rcv SYN      --> SYN-RECEIVED   send SYN+ACK
client SYN-SENT      --rcv SYN+ACK  --> ESTABLISHED    send ACK
server SYN-RECEIVED  --rcv ACK      --> ESTABLISHED
client ESTABLISHED   --close        --> FIN-WAIT-1     send FIN
server ESTABLISHED   --close        --> FIN-WAIT-1     send FIN
client FIN-WAIT-1    --rcv FIN      --> CLOSING        send ACK
server FIN-WAIT-1    --rcv FIN      --> CLOSING        send ACK
client CLOSING       --rcv ACK      --> TIME-WAIT
server CLOSING       --rcv ACK      --> TIME-WAIT
client TIME-WAIT     --2MSL timeout --> CLOSED
server TIME-WAIT     --2MSL timeout --> CLOSED

Error: client: 'rcv FIN' not valid in CLOSED

In the second scenario both FINs cross in the network, so both sides go through CLOSING and both end in TIME-WAIT. The last line shows that a FIN makes no sense for a socket that is CLOSED; our simple table rejects it, while a real TCP stack would answer it with an RST.


RST: Aborting a Connection

FIN is the polite goodbye; RST is hanging up the phone. Common cases:

  • A SYN arrives for a port where nothing is listening. The host replies with RST, and the client application sees "Connection refused".

  • An application closes a socket while unread data is still in its receive buffer, or chooses to abort the connection.

  • A segment arrives for a connection the host does not know about (for example, after a reboot).

An RST does not get an ACK. The connection is dropped immediately (usually straight to CLOSED) and any data not yet delivered may be lost. There is no TIME-WAIT after an RST.


Seeing TCP States on a Real Machine

You can watch these states on your own computer:

# Linux: all TCP sockets, numeric addresses, with their states
ss -tan

# Linux: count sockets in each state
ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c

# Linux: only connections in TIME-WAIT
ss -tan state time-wait

# Windows / macOS
netstat -an -p tcp

On a busy web server you will typically see one LISTEN socket on port 443, many ESTABLISHED connections, and some TIME-WAIT entries. The state names in the output will match the table above (with small spelling differences such as ESTAB or SYN-RECV).


Real Problems You Can Diagnose with States

What You See

Likely Cause

Thousands of sockets in SYN-RECEIVED

A SYN flood attack: many SYNs whose handshake is never completed, filling the server's queue of half-open connections. SYN cookies are a common defence.

Many sockets stuck in CLOSE-WAIT

An application bug: the peer closed, but your program never calls close() on the socket. TCP cannot leave CLOSE-WAIT until the application closes.

Many sockets in TIME-WAIT

Normal on the side that closes first, especially when opening many short connections. Reusing connections (HTTP keep-alive, connection pools) reduces it.

Client stuck in SYN-SENT

The SYN or SYN-ACK is being dropped, often by a firewall. The client times out instead of getting "connection refused".

Many sockets in FIN-WAIT-2

The peer acknowledged our FIN but never sends its own FIN, for example because the remote application did not close. Many systems put a timeout on this state.


Common Mistakes

  • Reading Data Offset as bytes. It is in 4-byte words. A value of 5 means 20 bytes, not 5.

  • Thinking sequence numbers count segments. They count bytes. A 1000-byte segment advances the sequence number by 1000.

  • Forgetting that SYN and FIN consume one sequence number. The ACK to a SYN with seq = x is x + 1, not x.

  • Saying TIME-WAIT is on the server. It is on whichever side closes first. That can be the client or the server.

  • Mixing up CLOSE-WAIT and TIME-WAIT. CLOSE-WAIT is on the passive closer and waits for the local application; TIME-WAIT is on the active closer and waits for a timer.

  • Assuming the header is always 20 bytes. SYN segments almost always carry options, so they are usually longer.

  • Saying the maximum window is 65,535 bytes. That is true only without the Window Scale option.


Interview Questions and Tips

Q: What is the minimum and maximum size of the TCP header?
20 bytes and 60 bytes, because the 4-bit Data Offset counts 32-bit words (max 15 × 4 = 60).

Q: Which side enters TIME-WAIT and why?
The active closer, for 2 × MSL, to resend the final ACK if needed and to let old duplicate segments expire before the same 4-tuple is reused.

Q: Your server shows thousands of CLOSE-WAIT connections. What is wrong?
Clients have closed their side, but the server application is not closing its sockets. It is a bug in the application (often a missing close in an error path), not in TCP.

Q: How many states does TCP have?
11: CLOSED, LISTEN, SYN-SENT, SYN-RECEIVED, ESTABLISHED, FIN-WAIT-1, FIN-WAIT-2, CLOSE-WAIT, CLOSING, LAST-ACK, TIME-WAIT.

Q: Why does TCP use a pseudo-header in the checksum?
To detect segments delivered to the wrong host or protocol, since the TCP header itself does not contain IP addresses.

Q: If seq = 2000 and the segment carries 700 bytes, what ACK will the receiver send?
2700 (the next byte expected), assuming all earlier bytes have arrived.

Tip: when drawing the state diagram in an interview, draw the "happy path" first (client: CLOSED → SYN-SENT → ESTABLISHED → FIN-WAIT-1 → FIN-WAIT-2 → TIME-WAIT → CLOSED; server: CLOSED → LISTEN → SYN-RECEIVED → ESTABLISHED → CLOSE-WAIT → LAST-ACK → CLOSED). Then add CLOSING and simultaneous open as extras.

Conclusion

The TCP header carries everything TCP needs to do its job: ports to find the application, sequence and ACK numbers for reliability and ordering, flags to open and close connections, the window for flow control, a checksum for error detection, and options such as MSS, window scaling and SACK.

The TCP state diagram describes the life of a connection through 11 states, from LISTEN and SYN-SENT, through ESTABLISHED, to the closing states and TIME-WAIT.

The easiest way to remember them is:

Header length = Data Offset × 4 (20 to 60 bytes)

SYN and FIN each use one sequence number; ACK = next byte expected

Max throughput ≤ Window / RTT

Active closer → FIN-WAIT-1 → FIN-WAIT-2 → TIME-WAIT (2 × MSL)

Passive closer → CLOSE-WAIT → LAST-ACK → CLOSED