The Transmission Control Protocol (TCP) is the cornerstone transport-layer protocol of the Internet, designed to convert an unreliable, packet-switched network layer into a reliable, ordered, and flow-controlled byte-stream service. To achieve these properties, TCP utilizes highly structured segment formats and a complex, stateful connection management lifecycle.
Unlike simple protocols such as UDP, TCP segments include significant metadata to manage state, flow boundaries, and error recovery. A TCP segment is encapsulated within an IP datagram and consists of an structural header followed by application data.
The TCP header has a minimum length of 20 bytes and can expand up to 60 bytes when options are present.
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 | |U|A|P|R|S|F| |
| Offset| Reserved |R|C|S|S|Y|I| Window |
| | |G|K|H|T|N|N| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | Urgent Pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options (0 to 40 bytes) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Data |
| ... |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ACK flag is set. It specifies the next byte the receiver expects to receive, serving as a cumulative acknowledgment.To guarantee end-to-end delivery safety, the checksum calculation includes a pseudoheader prepended to the TCP segment. This step verifies that the segment has reached the correct destination host and transport protocol.
+---------------------------------------------------------+
| 32-bit Source IP Address |
+---------------------------------------------------------+
| 32-bit Destination IP Address |
+---------------------------------------------------------+
| Zero (8 bits) | Protocol (8) | TCP Length (16) |
+---------------------------------------------------------+TCP views data as an ordered, continuous stream of bytes. Rather than numbering individual segments, TCP numbers each byte in the stream.
If an application initiates a connection and wants to transmit a file of size bytes, TCP assigns a sequential index to every byte. The sequence number of a segment is defined by the index of its first payload byte:
TCP's acknowledgment system is cumulative, meaning that an acknowledgment number indicates that all bytes up to have been successfully received, and the receiver is expecting byte next.
Suppose a connection transfers bytes with an over five segments of bytes each:
\text{Segment 1:} & \quad \text{SeqNo} = 10,001 \quad (\text{Bytes } 10,001 \text{ to } 11,000) \\ \text{Segment 2:} & \quad \text{SeqNo} = 11,001 \quad (\text{Bytes } 11,001 \text{ to } 12,000) \\ \text{Segment 3:} & \quad \text{SeqNo} = 12,001 \quad (\text{Bytes } 12,001 \text{ to } 13,000) \\ \text{Segment 4:} & \quad \text{SeqNo} = 13,001 \quad (\text{Bytes } 13,001 \text{ to } 14,000) \\ \text{Segment 5:} & \quad \text{SeqNo} = 14,001 \quad (\text{Bytes } 14,001 \text{ to } 15,000) \end{aligned}$$ If Segment 2 is lost but Segments 1, 3, and 4 arrive safely, the receiver sends an $\text{ACK} = 11,001$. Even though bytes $12,001$ to $14,000$ have arrived, they cannot be acknowledged because TCP's cumulative structure requires the next expected contiguous byte. --- ## 3. TCP Connection Management (The Lifecycle) TCP is a connection-oriented protocol that establishes a logical, virtual path between end-hosts. This lifecycle consists of three distinct phases: Connection Establishment, Data Transfer, and Connection Termination. ### 3.1 Connection Establishment: Three-Way Handshake To prevent stale or duplicate connection attempts from disrupting service, TCP requires a three-way handshake to synchronize Initial Sequence Numbers ($\text{ISN}$). ```text Client (Active Open) Server (Passive Open) | | | 1. SYN (Seq = x, ACK = 0, Flags = SYN) | |--------------------------------------------------->| [State: SYN-RCVD] | | | 2. SYN-ACK (Seq = y, Ack = x + 1, Flags = SYN+ACK)| |<---------------------------------------------------| | | | 3. ACK (Seq = x + 1, Ack = y + 1, Flags = ACK) | |--------------------------------------------------->| [State: ESTABLISHED] V V ``` 1. **SYN:** The client sends a segment with the `SYN` flag set and an initial sequence number $x$ ($\text{ISN}_{\text{client}}$). * *Rule:* A `SYN` segment cannot carry payload but consumes exactly one sequence number. 2. **SYN-ACK:** The server responds with a segment where both `SYN` and `ACK` flags are set. It advertises its own initial sequence number $y$ ($\text{ISN}_{\text{server}}$) and sets the acknowledgment field to $x + 1$. * *Rule:* A `SYN-ACK` segment consumes exactly one sequence number. 3. **ACK:** The client sends an acknowledgment segment back to the server. The sequence number is updated to $x + 1$ and the acknowledgment number is set to $y + 1$. * *Rule:* An `ACK` segment that contains no data consumes zero sequence numbers. ### 3.2 Connection Termination TCP connections are full-duplex, meaning both directions of transmission must be closed independently. This can be done via a symmetric four-way handshake or a half-close. ```text Host A (Active Close) Host B (Passive Close) | | | 1. FIN (Seq = u, Ack = v, Flags = FIN+ACK) | |--------------------------------------------------->| [State: CLOSE-WAIT] | | | 2. ACK (Seq = v, Ack = u + 1, Flags = ACK) | |<---------------------------------------------------| | | | (Host B sends any remaining data segments...) | | | | 3. FIN (Seq = w, Ack = u + 1, Flags = FIN+ACK) | |<---------------------------------------------------| [State: LAST-ACK] | | | 4. ACK (Seq = u + 1, Ack = w + 1, Flags = ACK) | |--------------------------------------------------->| V V [State: TIME-WAIT (2MSL)] [State: CLOSED] ``` #### Why is the TIME-WAIT state necessary? The active closer enters the `TIME-WAIT` state and starts a timer equal to $2 \times \text{MSL}$ (Maximum Segment Lifetime). This is required for two reasons: 1. **Ensuring the final ACK is received:** If the final `ACK` is lost, Host B will timeout and retransmit its `FIN`. The active closer must remain in a valid state to retransmit its final `ACK`. 2. **Draining duplicate segments:** It allows lingering packets from the current connection to expire in the network, preventing them from corrupting future connections that use the same socket pair (IP/Port combinations). --- ## 4. The TCP Finite State Machine (FSM) The complex operational states of a TCP client and server are governed by the following state machine: ```text +---------+ | CLOSED | +---------+ / \ Passive / \ Active Open Open / \ (Send SYN) V V +---------+ +----------+ | LISTEN | | SYN-SENT | +---------+ +----------+ / \ / \ RCV SYN / \ Send / Rcv SYN \ Rcv SYN+ACK Send SYN / \ SYN / Send ACK \ Send ACK V V V V +----------+ +----------+ +-------------+ | SYN-RCVD | | SYN-SENT | | ESTABLISHED | +----------+ +----------+ +-------------+ | | | Rcv ACK | Active Close | (No action) | Send FIN V V +-------------+ +-------------+ | ESTABLISHED | | FIN-WAIT-1 | +-------------+ +-------------+ / | \ Rcv ACK / | \ Rcv FIN No action/ | \ Send ACK V |Rcv FIN+ V +----------+ | ACK | CLOSING | |FIN-WAIT-2| |Send ACK +-----------+ +----------+ | | | | | Rcv ACK Rcv FIN | | | No action Send ACK | V V V +-----------+ +-----------+ +-->| TIME-WAIT |<---| TIME-WAIT | +-----------+ +-----------+ | | 2MSL Timer V +---------+ | CLOSED | +---------+ ``` --- ## 5. Flow Control and Silly Window Syndrome Flow control ensures that a fast sender does not overwhelm a slow receiver's buffer space. TCP implements this using a sliding window. ### 5.1 Sliding Window Mechanics The receiver advertises its current receive buffer capacity using the `rwnd` field. This dynamically constrains the sender's window size: $$\text{Effective Window Size} \le \min(\text{cwnd}, \text{rwnd})$$ where $\text{cwnd}$ is the congestion window, and $\text{rwnd}$ is the receiver's advertised window. ```text <--- Sent, ACKed ---> <----- Sent, UnACKed -----> <--- Can Send Immediately ---> +---------------------+---------------------------+-------------------------------+ Byte | 100 101 102 103 104 | 105 106 107 108 109 110 111 | 112 113 114 115 116 117 118 | ... +---------------------+---------------------------+-------------------------------+ ^ ^ ^ | | | Left-Wall NextSeqNo Right-Wall (last_ackNo) (last_ackNo + rwnd) ``` To prevent the **shrinking of the window** (which can prematurely truncate transmitted data), the receiver must not close the right-hand wall faster than the left-hand wall advances. This is guaranteed by ensuring: $$\text{new\_ackNo} + \text{new\_rwnd} \ge \text{last\_ackNo} + \text{last\_rwnd}$$ ### 5.2 Silly Window Syndrome (SWS) Silly Window Syndrome occurs when data is exchanged in very small segments (e.g., 1 byte at a time), causing the overhead of the IP and TCP headers to dwarf the actual payload. #### 5.2.1 Sender-Side Solution: Nagle's Algorithm Nagle's algorithm dictates that: 1. The sender transmits the first chunk of data immediately, even if it is small. 2. Subsequent small writes are buffered until either a maximum-sized segment ($\text{MSS}$) can be assembled, or the outstanding data has been acknowledged ($\text{ACK}$ received). #### 5.2.2 Receiver-Side Solutions If the receiving application reads data very slowly, it may advertise a window size of just a few bytes. * **Clark's Solution:** The receiver avoids advertising small window increases. It advertises a window size of $0$ until it has enough buffer space to accommodate a maximum segment size ($\text{MSS}$) or until half of its receive buffer is empty. * **Delayed Acknowledgment:** The receiver delays sending acknowledgments to allow its buffer to clear and to bundle multiple incoming segments into a single cumulative `ACK`. This delay is typically capped at $500 \text{ ms}$. --- ## 6. Error Control and Retransmission Timers TCP's reliability is built on three pillars: checksums, cumulative acknowledgments, and retransmission timeouts (RTO). ### 6.1 RTO Calculations (RFC 6298) The Retransmission Timeout ($\text{RTO}$) must adjust dynamically to varying network conditions. Setting the $\text{RTO}$ too low causes unnecessary retransmissions, while setting it too high delays recovery. 1. **First Measurement:** $$\text{RTT}_S = \text{RTT}_M$$ $$\text{RTT}_D = \frac{\text{RTT}_M}{2}$$ $$\text{RTO} = \text{RTT}_S + 4 \times \text{RTT}_D$$ 2. **Subsequent Measurements:** When a new sample measurement $\text{RTT}_M$ is acquired, the Smoothed RTT ($\text{RTT}_S$) and RTT Deviation ($\text{RTT}_D$) are updated using the smoothing factors $\alpha = 0.125$ and $\beta = 0.25$: $$\text{RTT}_S = (1 - \alpha) \times \text{RTT}_S + \alpha \times \text{RTT}_M$$ $$\text{RTT}_D = (1 - \beta) \times \text{RTT}_D + \beta \times |\text{RTT}_S - \text{RTT}_M|$$ $$\text{RTO} = \text{RTT}_S + 4 \times \text{RTT}_D$$ *Note:* Standard implementations enforce a minimum RTO limit (typically $1 \text{ second}$). ### 6.2 Karn's Algorithm If a segment is retransmitted, the arriving acknowledgment is ambiguous—it is unclear whether the `ACK` is for the original transmission or the retransmission. **Karn's Algorithm** resolves this: 1. Do not measure $\text{RTT}_M$ for any retransmitted segments. 2. Double the $\text{RTO}$ (exponential backoff) for each consecutive retransmission of a segment until an acknowledgment for a new segment is received. ### 6.3 Fast Retransmit Waiting for the RTO timer to expire can cause significant delays. If a segment is lost, subsequent out-of-order segments will prompt the receiver to immediately generate duplicate ACKs. ```text Sender Receiver | | | 1. Segment 1 (Seq = 1000) | |----------------------------------------------------------->| (Receives 1000) | | | 2. Segment 2 (Seq = 2000) [LOST] | | x | | | | 3. Segment 3 (Seq = 3000) | |----------------------------------------------------------->| (Out of order, sends ACK 2000) | | <-- Duplicate ACK 1 | 4. Segment 4 (Seq = 4000) | |----------------------------------------------------------->| (Out of order, sends ACK 2000) | | <-- Duplicate ACK 2 | 5. Segment 5 (Seq = 5000) | |----------------------------------------------------------->| (Out of order, sends ACK 2000) | | <-- Duplicate ACK 3 | | | * Receives 3 Duplicate ACKs! | | * Immediately Resends Segment 2 (Seq = 2000) | |<-----------------------------------------------------------| ``` When the sender receives **three duplicate ACKs** (four identical ACKs in total), it assumes the segment indicated by the ACK has been lost and immediately retransmits it before its retransmission timer expires. --- ## 7. TCP Options The TCP header can append up to 40 bytes of structural options to optimize performance. ### 7.1 Key Option Identifiers * **Maximum Segment Size (MSS):** Negotiated during connection establishment (SYN packets), it defines the largest payload size (excluding TCP/IP headers) that the host can accept in a single segment. * **Window Scale Factor:** The standard 16-bit window size field limits the advertised window to $65,535$ bytes. The Window Scale option specifies a shift count $S$ (up to 14), scaling the window up to $2^{16 + S}$ bytes (nearly $1 \text{ Gigabyte}$). This is critical for high-bandwidth-delay product (LFN - "Long Fat Networks") links. * **Timestamp:** Provides precise RTT estimation and supports **PAWS** (Protection Against Wrapped Sequence numbers) by rejecting old duplicate packets in high-speed connections. * **SACK-Permitted and SACK:** Advertised in SYN packets, this allows the receiver to report non-contiguous data blocks received out-of-order using Selective Acknowledgment (SACK), helping the sender selectively retransmit only the missing packets. --- ## 8. Structural System Implementation Below is a standard C representation illustrating how raw systems programmatically interact with the TCP header structure. ```c #include <stdint.h> struct tcp_header { uint16_t src_port; // Source Port uint16_t dst_port; // Destination Port uint32_t seq_num; // Sequence Number uint32_t ack_num; // Acknowledgment Number #if __BYTE_ORDER == __LITTLE_ENDIAN uint8_t reserved:4, // Reserved 4 bits data_offset:4; // Header length (data offset) #elif __BYTE_ORDER == __BIG_ENDIAN uint8_t data_offset:4, // Header length (data offset) reserved:4; // Reserved 4 bits #endif uint8_t flags; // Control Flags: CWR, ECE, URG, ACK, PSH, RST, SYN, FIN uint16_t window_size; // Advertised Window Size (rwnd) uint16_t checksum; // Checksum (includes pseudo-header) uint16_t urgent_ptr; // Urgent Pointer }; ``` --- ## Summary * **TCP Header Flexibility:** The TCP header is highly flexible, scaling from 20 bytes up to 60 bytes using option fields such as MSS, Window Scaling, and Timestamps. * **Byte-Stream Semantics:** TCP numbers each individual byte in the connection stream, enabling continuous tracking and cumulative acknowledgments. * **Stateful Control:** Connection management utilizes a rigorous state transition structure (including the critical `2MSL` wait period in `TIME-WAIT`) to ensure clean resource cleanup. * **Flow and Congestion Management:** Through mechanisms like the sliding window, SWS resolutions, and dynamic RTO computations, TCP balances link and buffer constraints across varying network conditions.The structural formatting of TCP packets containing source/destination ports, sequence numbers, control flags, and optional fields used for end-to-end reliability.
The connection establishment protocol requiring three distinct message exchanges to synchronize sequence numbers and allocate resources.
A terminal connection state lasting for 2MSL (Maximum Segment Lifetime) to ensure delayed segments drain from the network and the final ACK is received.
A degradation of throughput occurring when small chunks of data are repeatedly transmitted, resolved by Nagle's algorithm and Clark's solution.
A dynamically computed timer based on Smoothed Round-Trip Time (RTT) and RTT Deviation, dictating when an unacknowledged segment must be resent.
Test your understanding with 5 questions
Given a TCP connection with a currently estimated Smoothed RTT (RTTS) of 80 ms and an RTT Deviation (RTTD) of 10 ms. If a new segment measurement yields a round-trip time (RTTM) of 120 ms, what are the newly computed RTTS and RTO (Retransmission Timeout) values? (Use alpha = 0.125, beta = 0.25, and use the old RTTS for the deviation computation as per RFC 6298).
Under Nagle's algorithm for resolving Silly Window Syndrome at the sender's side, when is a newly generated small segment of data transmitted?
A TCP connection is currently in the ESTABLISHED state. The client application initiates an active close. What sequence of state transitions will the client undergo if it receives a FIN segment while it is waiting in the FIN-WAIT-1 state?
Suppose a receiver using Selective Acknowledgment (SACK) has received bytes 1 to 2000 uncorrupted. Subsequently, a gap occurs, and the receiver gets segments spanning 3001 to 4000 and 4501 to 6000. Which of the following defines the correct ACK number and SACK blocks advertised back to the sender?
To prevent the 'shrinking' of the TCP send window, which mathematical inequality must a receiver guarantee when updating its advertised window (rwnd) and acknowledgment number (ackNo) relative to its last transmission?
URG flag is set.6 Modules
6 Modules