π§ How TCP Works
1. Connection Establishment: The 3-Way Handshake
To start a TCP session, both sides perform a three-step handshake:
- SYN β The client sends a synchronize (SYN) message to the server.
- SYN-ACK β The server responds with a SYN-ACK (synchronize-acknowledge).
- ACK β The client sends back an ACK, and the connection is established.
This ensures both parties are ready to start data transfer.
2. Data Transmission
- Segmentation: TCP breaks application data into manageable segments.
- Sequence Numbers: Each byte of data is assigned a number. These help with ordering and detecting loss.
- Acknowledgements (ACKs): The receiver sends ACKs back to confirm receipt of data.
3. Reliability Mechanisms
- Retransmission: If an ACK isnβt received in time, TCP resends the data.
- Checksums: Each segment includes a checksum to verify data integrity.
- Duplicate Data Handling: Duplicate segments are detected and discarded.
4. Flow Control (Sliding Window)
TCP uses a window size to control how much data can be sent before waiting for an ACK. This:
- Prevents sender from overwhelming the receiver.
- Allows multiple packets to be in transit (pipeline).
5. Congestion Control
To avoid overloading the network:
- Slow Start: TCP starts with a small congestion window (cwnd) and increases it exponentially.
- Congestion Avoidance: Once a threshold is reached, it grows linearly.
- Fast Retransmit & Fast Recovery: Handle loss without waiting for timeout.
6. Connection Termination: 4-Way Teardown
TCP closes a connection using a four-step process:
- FIN from one side
- ACK from the other
- FIN from the second side
- ACK from the first side
Each side closes independently.
Field |
Purpose |
Source/Destination Port |
Identifies sending and receiving application |
Sequence Number |
Indicates the position of data |
Acknowledgment Number |
Confirms received data |
Flags (SYN, ACK, FIN, etc.) |
Controls connection states |
Window Size |
Flow control mechanism |
Checksum |
Error detection |
π Typical Applications
TCP is used when data accuracy and order are more important than speed:
- Web browsing (HTTP, HTTPS)
- Email (SMTP, IMAP, POP3)
- File transfers (FTP)
- Remote terminals (SSH, Telnet)