TCP/UDP Transport Protocols & TCP State Transitions
Idea in plain words
TCP (Transmission Control Protocol) is connection-oriented, reliable, byte-stream oriented, and features flow/congestion control.
Exam tip
High-yield exam topic (Very High).
Explanation
The Transport Layer mediates communication between host applications. TCP provides full-duplex byte streams, sequencing, and acknowledgment mechanisms. The TCP state machine governs connection lifecycles: LISTEN -> SYN_RCVD -> ESTABLISHED -> FIN_WAIT_1 -> FIN_WAIT_2 -> TIME_WAIT -> CLOSED. The TIME_WAIT state prevents delayed duplicate packets from a previous connection from corrupting a new connection re-using the same 4-tuple (source IP, source port, dest IP, dest port). UDP avoids protocol overhead, making it ideal for DNS queries, real-time media streaming (RTP), and telemetry.
Key points
- UDP (User Datagram Protocol) is connectionless, unreliable, message-oriented, with zero handshake latency.
- TCP 3-Way Handshake: SYN (seq=x) -> SYN-ACK (seq=y, ack=x+1) -> ACK (ack=y+1).
- TCP 4-Way Teardown: FIN -> ACK -> FIN -> ACK; initiating endpoint enters TIME_WAIT state.
- TIME_WAIT duration is 2 * MSL (Maximum Segment Lifetime, typically 1 to 4 minutes) to allow lagging duplicate segments to expire and ensure the final ACK arrives.
Example
Example
A web browser downloading a webpage creates a TCP connection. If the client closes the connection, the client enters TIME_WAIT. Attempting to immediately restart a local server on the same port fails with EADDRINUSE unless SO_REUSEADDR is specified.
Code examples
/*
TCP State Machine Summary:
Client Server
| | (LISTEN)
|------- SYN --------->| (SYN_RCVD)
|<---- SYN + ACK ------|
|------- ACK --------->| (ESTABLISHED)
| |
|------- FIN --------->| (CLOSE_WAIT)
|<------ ACK ----------|
|<------ FIN ----------| (LAST_ACK)
|------- ACK --------->| (CLOSED)
(TIME_WAIT: 2MSL)
*/
Exam questions
- [10 Marks] Draw and thoroughly explain the TCP Connection Establishment (3-way handshake) and Connection Termination (4-way handshake) with packet headers.
- [5 Marks] What is the necessity of the TIME_WAIT state in TCP? Why is its duration set to 2MSL?