Transport Layer: TCP and UDP
The transport layer provides process-to-process delivery using ports (0 to 65535). A connection is identified by (source IP, source port, destination IP, destination port).
TCP vs UDP
| TCP | UDP | |
|---|---|---|
| Connection | Connection-oriented | Connectionless |
| Reliability | Acknowledgements, retransmission, ordering | None |
| Flow / congestion control | Yes | No |
| Overhead | Higher (20+ byte header) | Low (8 byte header) |
| Use | Web, email, file transfer | DNS, streaming, gaming, VoIP, QUIC |
TCP connection lifecycle
Three-way handshake Connection teardown
Client Server Client Server
SYN -------> FIN ------->
<------- SYN+ACK <------- ACK
ACK -------> <------- FIN
ACK ------->
States include LISTEN, SYN_SENT, ESTABLISHED, FIN_WAIT, TIME_WAIT.
Reliability
- Sequence numbers and acknowledgements order data and detect loss.
- Retransmission on timeout or on three duplicate ACKs (fast retransmit).
- Variants of sliding window: Go-Back-N and Selective Repeat.
Flow control vs congestion control
| Flow control | Congestion control | |
|---|---|---|
| Protects | The receiver | The network |
| Mechanism | Receiver window (rwnd) | Congestion window (cwnd) |
Throughput is limited by min(rwnd, cwnd).
Congestion control phases
- Slow start:
cwnddoubles every RTT up tossthresh. - Congestion avoidance:
cwndgrows by about 1 MSS per RTT. - On loss: multiplicative decrease (halve
cwnd); this AIMD pattern keeps the network stable.
Sockets
tcp_echo.py
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 9000))
server.listen()
conn, addr = server.accept()
conn.sendall(conn.recv(1024)) # echo
conn.close()
Loading Comments...