CN Notes
Practical guide to TCP and UDP protocols — segment structure, three-way handshake, flow control, congestion control, and when to use TCP vs UDP in real applications.
Introduction
The Transport Layer is the core of the TCP/IP protocol suite — so fundamental that the entire model is named after its two protocols: TCP (Transmission Control Protocol) and UDP (User Datagram Protocol). This layer provides end-to-end communication between applications running on different hosts, handling segmentation, port-based multiplexing, and (in TCP's case) reliable delivery.
While the OSI model describes the Transport Layer abstractly, the TCP/IP model defines it through two concrete protocols that power the entire internet. Every web page you load uses TCP. Every DNS query uses UDP. Understanding how these protocols actually work is essential for any networking professional.
TCP vs UDP: The Two Workhorses
The Transport Layer gives applications a choice between two fundamentally different approaches to communication:
| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented (handshake required) | Connectionless (send immediately) |
| Reliability | Guaranteed delivery with acknowledgments | Best-effort, no guarantees |
| Ordering | Maintains packet order | No ordering guarantee |
| Flow Control | Yes (sliding window) | No |
| Congestion Control | Yes (slow start, AIMD) | No |
| Header Size | 20-60 bytes | 8 bytes |
| Speed | Slower (overhead) | Faster (minimal overhead) |
| Use Cases | Web, email, file transfer | DNS, streaming, gaming |
TCP: Transmission Control Protocol
TCP Segment Structure
Every TCP segment contains a header with control information followed by the data payload:
The Three-Way Handshake
TCP establishes a connection using a three-step process that synchronizes sequence numbers between client and server:
| │─── SYN (seq=100) ────────────────►│ Step 1 | Client initiates |
| │◄── SYN-ACK (seq=300, ack=101) ───│ Step 2 | Server acknowledges |
| │─── ACK (seq=101, ack=301) ───────►│ Step 3 | Client confirms |
Why three steps? Both sides need to agree on initial sequence numbers. Two steps would leave the server unsure if the client received its sequence number.
TCP Connection Termination (Four-Way Handshake)
Flow Control: Sliding Window
TCP uses a sliding window mechanism to prevent a fast sender from overwhelming a slow receiver. The receiver advertises its available buffer space in the Window Size field.
Congestion Control
TCP implements congestion control to prevent network overload. The four main algorithms work together:
1. Slow Start: Begin with a small congestion window (cwnd = 1 MSS), double it each RTT until reaching the threshold.
2. Congestion Avoidance: After threshold, increase cwnd by 1 MSS per RTT (linear growth).
3. Fast Retransmit: On receiving 3 duplicate ACKs, retransmit the lost segment immediately without waiting for timeout.
4. Fast Recovery: After fast retransmit, halve the threshold and enter congestion avoidance (skip slow start).
TCP Retransmission
When a segment is lost, TCP detects it through:
- Timeout: No ACK received within RTO (Retransmission Timeout)
- Triple Duplicate ACK: Receiver sends the same ACK three times, indicating a gap
UDP: User Datagram Protocol
UDP Datagram Structure
UDP has a minimal 8-byte header — just enough for port multiplexing and error detection:
| Source Port (16 bits) | Destination Port (16 bits) |
|---|---|
| Length (16 bits) | Checksum (16 bits) |
Why Use UDP?
UDP is preferred when:
- Latency matters more than reliability (live video, gaming)
- Messages are small and independent (DNS queries)
- Application handles its own reliability (QUIC protocol)
- Multicast/broadcast is needed (service discovery)
- Occasional packet loss is acceptable (sensor data, VoIP)
UDP in Practice
import socket
# UDP Server - No connection needed
def udp_server():
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('0.0.0.0', 9999))
print("UDP Server listening on port 9999")
while True:
data, client_addr = server.recvfrom(1024)
print(f"Received from {client_addr}: {data.decode()}")
# Send response back to client
server.sendto(b"ACK: " + data, client_addr)
# UDP Client - Fire and forget
def udp_client():
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b"Hello UDP!", ('127.0.0.1', 9999))
# Optional: wait for response with timeout
client.settimeout(2.0)
try:
response, server = client.recvfrom(1024)
print(f"Server replied: {response.decode()}")
except socket.timeout:
print("No response received (expected with UDP)")
client.close()Port Numbers and Multiplexing
The Transport Layer uses port numbers to deliver data to the correct application. This is called multiplexing (combining multiple streams) and demultiplexing (separating them at the destination).
| │ Browser | 49152 ─────────TCP────────► Web Server :443 │ |
| │ Browser | 49153 ─────────TCP────────► Web Server :443 │ |
| 49154 ─────────TCP────────► SMTP :25 │ | |
| │ DNS | 49155 ─────────UDP────────► DNS Server :53 │ |
Each connection is uniquely identified by a 4-tuple: (Source IP, Source Port, Destination IP, Destination Port).
TCP vs UDP: Decision Framework
# How to choose between TCP and UDP
def choose_protocol(requirements):
"""Decision framework for protocol selection"""
if requirements.get("guaranteed_delivery"):
return "TCP" # Email, file transfer, web pages
if requirements.get("real_time"):
return "UDP" # Video calls, gaming, live streaming
if requirements.get("small_messages") and requirements.get("low_latency"):
return "UDP" # DNS queries, NTP
if requirements.get("multicast"):
return "UDP" # Only UDP supports multicast
if requirements.get("ordered_delivery"):
return "TCP" # Database replication, messaging
return "TCP" # Default: TCP is safer choice
# Modern approach: QUIC (UDP + reliability at application layer)
# Used by HTTP/3, provides TCP-like reliability over UDPPerformance Metrics
| Metric | TCP | UDP | Impact |
|---|---|---|---|
| Connection Setup | 1.5 RTT (3-way handshake) | 0 RTT | UDP wins for first packet |
| Min Header Overhead | 20 bytes/segment | 8 bytes/datagram | UDP is 60% lighter |
| Throughput | Limited by cwnd and rwnd | Limited only by link | UDP can burst faster |
| Latency | Head-of-line blocking | Independent datagrams | UDP has lower tail latency |
| Reliability | 100% (retransmission) | 0% (application handles) | TCP guarantees delivery |
Common Issues and Troubleshooting
Issue 1: TCP Connection Refused
Cause: No application listening on the target port, or firewall blocking. Diagnosis: telnet host port or nc -zv host port Solution: Verify service is running, check firewall rules.
Issue 2: TCP Connection Timeout
Cause: Packets being dropped, routing issues, or host unreachable. Diagnosis: traceroute to identify where packets are lost. Solution: Check network path, MTU issues, routing tables.
Issue 3: Poor TCP Throughput
Cause: Small window size, high packet loss, or high RTT. Diagnosis: ss -i to check cwnd, window size, and retransmissions. Solution: Enable window scaling, tune buffer sizes, reduce RTT.
Issue 4: UDP Packet Loss
Cause: Network congestion, buffer overflow, or rate limiting. Diagnosis: Monitor packet counts at sender and receiver. Solution: Implement application-level acknowledgments, add jitter buffer.
Interview Questions
Q1: Explain the TCP three-way handshake and why it needs three steps.
Answer: The three-way handshake (SYN → SYN-ACK → ACK) establishes a TCP connection by synchronizing sequence numbers. Three steps are needed because both sides must share AND confirm their initial sequence numbers. If only two steps were used, the server would send its sequence number but never know if the client received it, creating a half-open connection vulnerability.
Q2: How does TCP handle packet loss?
Answer: TCP detects loss through two mechanisms: (1) Retransmission Timeout — if no ACK arrives within the calculated RTO, the segment is retransmitted; (2) Triple Duplicate ACK — when the receiver gets out-of-order segments, it sends duplicate ACKs for the last correctly received segment. Three duplicate ACKs trigger fast retransmit without waiting for timeout, significantly improving recovery speed.
Q3: Why would you choose UDP over TCP for a video streaming application?
Answer: Video streaming prioritizes low latency over perfect reliability. With TCP, a single lost packet causes head-of-line blocking — all subsequent data waits until the lost packet is retransmitted. With UDP, lost frames are simply skipped, and the video continues playing with minor quality reduction. The slight visual glitch is far better than the buffering delay TCP would cause.
Q4: What is TCP congestion control and why is it necessary?
Answer: TCP congestion control prevents senders from overwhelming the network. Without it, multiple TCP connections would flood the network simultaneously, causing massive packet loss and collapse. The algorithms (Slow Start, Congestion Avoidance, Fast Retransmit, Fast Recovery) dynamically adjust the sending rate based on detected network capacity, ensuring fair bandwidth sharing among all connections.
Q5: How does multiplexing work at the Transport Layer?
Answer: Multiplexing uses port numbers to direct data to the correct application. Each TCP connection is identified by a unique 4-tuple (source IP, source port, destination IP, destination port). This allows multiple applications on the same host to communicate simultaneously. A web server on port 443 can handle thousands of concurrent connections because each has a unique client IP:port combination.
Quick Revision Notes
- TCP = Connection-oriented, reliable, ordered delivery (3-way handshake)
- UDP = Connectionless, fast, best-effort delivery (no handshake)
- Port numbers = 0-1023 well-known, 1024-49151 registered, 49152-65535 ephemeral
- Flow control = Receiver advertises window size to prevent buffer overflow
- Congestion control = Sender adjusts cwnd based on network feedback
- MSS = Maximum Segment Size (typically 1460 bytes for Ethernet)
- RTT = Round Trip Time; affects timeout calculations and throughput
- 4-tuple = (Src IP, Src Port, Dst IP, Dst Port) identifies a connection
Summary
The TCP/IP Transport Layer provides the critical bridge between applications and the network. TCP delivers reliability through handshakes, acknowledgments, retransmission, flow control, and congestion control — essential for web browsing, email, and file transfers. UDP delivers speed through minimal overhead — essential for DNS, streaming, and real-time communication. Mastering both protocols and knowing when to use each is a fundamental skill for any network engineer or developer.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Transport Layer in TCP/IP Model.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Computer Networks topic.
Search Terms
computer-network-master, computer networks, computer, network, master, tcp, model, transport
Related Computer Networks Topics