The Reliable Protocol
TCP (Transmission Control Protocol) is the workhorse of the internet. It provides reliable, ordered, error-checked delivery of data. When you load a webpage, send an email, or transfer a file, TCP makes sure every byte arrives correctly.
TCP is like a certified mail service β every piece of data is tracked, acknowledged, and retransmitted if lost. It's slower than UDP, but you can trust it with your data.
The Three-Way Handshake
Before TCP can send data, it establishes a connection using the famous three-way handshake:
Client Server
β β
βββββ SYN βββββββββββββββββββββββ Step 1: Client says "I want to connect"
β β
βββββ SYN-ACK ββββββββββββββββββ Step 2: Server says "OK, I'm ready too"
β β
βββββ ACK βββββββββββββββββββββββ Step 3: Client says "Great, let's start"
β β
βββββββββββββββββββββββββββββββββ
β Connection Established β
βββββββββββββββββββββββββββββββββ
This handshake ensures both sides are ready and agree on initial sequence numbers. It's like two people confirming they're both on the phone before starting a conversation.
How TCP Ensures Reliability
- Sequence Numbers β Every byte of data is numbered. The receiver can detect missing data and reorder out-of-order segments.
- Acknowledgments (ACKs) β The receiver sends ACKs to confirm which data it has received. If the sender doesn't receive an ACK within a timeout period, it retransmits the data.
- Checksum β Each segment includes a checksum. If the data is corrupted in transit, the receiver detects it and discards the segment.
- Flow Control β The receiver tells the sender how much buffer space it has available (the window size). This prevents the sender from overwhelming the receiver.
- Congestion Control β TCP monitors network conditions and slows down when congestion is detected. Algorithms like Slow Start, Congestion Avoidance, Fast Retransmit, and Fast Recovery manage this.
TCP Segment Structure
ββββββββββββββ¬βββββββββββββ¬βββββββββββββββββββββββββββ
β Src Port β Dst Port β β
β (16 bits) β (16 bits) β β
ββββββββββββββΌβββββββββββββ€ TCP Header β
β Sequence Number β (20-60 bytes) β
β (32 bits) β β
ββββββββββββββββββββββββββββ€ β
β Acknowledgment Number β β
β (32 bits) β β
βββββββββ¬ββββββ¬βββββββββββββ€ β
βHeader βFlagsβ Window β β
βLength βSYN β Size β β
β βACK β (16 bits) β β
β βFIN β β β
β βRST β β β
ββββββββββββββ΄βββββββββββββΌβββββββββββββββββββββββββββ€
β Checksum β Urgent Ptrβ Data β
ββββββββββββββ΄βββββββββββββ΄βββββββββββββββββββββββββββ
TCP Connection Termination
When a TCP connection is done, it's closed with a four-way handshake:
Client Server
β β
βββββ FIN βββββββββββββββββββββββ "I'm done sending"
βββββ ACK ββββββββββββββββββββββ "Acknowledged"
βββββ FIN ββββββββββββββββββββββ "I'm done too"
βββββ ACK βββββββββββββββββββββββ "Acknowledged"
β β
β Connection Closed β
Both sides must independently close their sending direction. This ensures all data is delivered before the connection is fully terminated.