Skip to main content

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​

TCPUDP
ConnectionConnection-orientedConnectionless
ReliabilityAcknowledgements, retransmission, orderingNone
Flow / congestion controlYesNo
OverheadHigher (20+ byte header)Low (8 byte header)
UseWeb, email, file transferDNS, 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 controlCongestion control
ProtectsThe receiverThe network
MechanismReceiver window (rwnd)Congestion window (cwnd)

Throughput is limited by min(rwnd, cwnd).

Congestion control phases​

  1. Slow start: cwnd doubles every RTT up to ssthresh.
  2. Congestion avoidance: cwnd grows by about 1 MSS per RTT.
  3. 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()