TCP (Transmission Control Protocol) is a connection-oriented, reliable transport protocol that ensures data is delivered correctly and in order. It's one of the core protocols of the Internet, sitting in Layer 4 of the OSI model.
Before any data is sent, TCP establishes a connection using the famous three-way handshake. Think of it as knocking on the door and waiting to be invited in.
Prevents overwhelming the receiver by controlling data transmission rate using sliding window protocol.
// Sliding Window Protocol
Window Size =
min(receiver_buffer,
network_capacity)
Sender waits for ACK
before sending more data
Uses checksums to detect corrupted data and requests retransmission automatically.
// Checksum Calculation
checksum =
sum_of_all_bytes % 65536
if (checksum != received) {
request_retransmission();
}
Manages network traffic to prevent congestion collapse using slow-start and AIMD algorithms.
// Slow Start Algorithm
cwnd = 1; // Congestion Window
while (cwnd < ssthresh) {
cwnd *= 2; // Exponential
}
// Then: linear growth
Sequence numbers ensure packets arrive at the application in correct order, regardless of network routing.
// Sequence Numbers
seq_num =
initial_seq + bytes_sent
Receiver buffers
out-of-order packets,
delivers in sequence
Every TCP packet has a minimum 20-byte header carrying critical control information:
| Field | Size | Purpose |
|---|---|---|
| Source Port | 16 bits | Sender's port number (identifies sending application) |
| Dest Port | 16 bits | Receiver's port number (identifies destination app) |
| Sequence Number | 32 bits | Position of this segment in the byte stream |
| Acknowledgment | 32 bits | Next expected byte from the other side |
| Header Length | 4 bits | Length of the TCP header in 32-bit words |
| Flags (Control) | 6 bits | SYN, ACK, FIN, RST, PSH, URG control bits |
| Window Size | 16 bits | Number of bytes receiver can accept (flow control) |
| Checksum | 16 bits | Error detection over header and data |
| Urgent Pointer | 16 bits | Points to urgent data (when URG flag set) |
| Options | Variable | Optional: MSS, window scaling, timestamps |
| Data | Variable | Application payload |
TCP connections move through well-defined states during their lifecycle:
| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented (handshake) | Connectionless (fire & forget) |
| Reliability | High — guaranteed delivery | Low — best effort only |
| Ordering | Guaranteed in-order | Not guaranteed |
| Speed | Slower (overhead of ACKs) | Faster (minimal overhead) |
| Header Size | 20 bytes minimum | Only 8 bytes |
| Flow Control | Yes (sliding window) | No |
| Congestion Control | Yes (slow start, AIMD) | No |
| Use Cases | Web, email, file transfer, SSH | Gaming, streaming, DNS, VoIP |