Transport Layer
Open in the Padhaiko app5.1 Transport layer functions and services
While the network layer provides host-to-host (logical IP) delivery across interconnected networks, an end host typically executes dozens of communicating applications simultaneously (e.g., a web browser, SSH terminal, and email client). The Transport Layer (Layer 4) bridges this gap by delivering process-to-process communication between application processes running on different hosts.
Core Functions of the Transport Layer
- Process-to-Process Delivery: Routes segments to the exact target application process using port numbers (–).
- Segmentation and Reassembly: Splits large application messages into transport-layer segments (or datagrams) sized to fit network-layer MTUs, and reassembles them in order at the receiver.
- Multiplexing and Demultiplexing: Aggregates data streams from multiple upper-layer sockets into a single network interface at the sender, and distributes arriving segments to the correct sockets at the receiver.
- Connection Control: Supports either connectionless delivery (UDP) or connection-oriented session establishment, maintenance, and teardown (TCP).
- Flow Control: Prevents a fast sender from overwhelming a slower receiver's finite buffer memory.
- Error Control: Detects corrupted, lost, out-of-order, or duplicated segments and triggers retransmission when reliability is required.
- Congestion Control: Regulates transmission rates based on observed network congestion (packet loss, ECN, or RTT inflation) to protect shared router queues.
Types of Transport Layer Services
- Reliable, Connection-Oriented Service (TCP): Guarantees in-order, error-free, non-duplicated byte-stream delivery after an explicit handshake.
- Unreliable, Connectionless Service (UDP): Provides lightweight, best-effort datagram delivery with minimal header overhead and no handshake or retransmission delay—ideal for real-time audio/video, DNS lookups, and SNMP.
5.2 Elements of transport layer protocols: process-to-process communication, addressing, multiplexing and de-multiplexing, segmentation and reassembly, error control, flow control
1. Process-to-Process Communication and Addressing
Network-layer IP addresses identify hosts, whereas transport-layer port numbers identify individual processes (endpoints) inside a host. Together, an IP address and a port number form a socket address (e.g., 192.168.1.10:443).
IANA divides the port space (–) into three ranges:
| Range | Category | Usage |
|---|---|---|
| – | Well-Known Ports | Standardized system services (HTTP 80, HTTPS 443, DNS 53, SSH 22, FTP 20/21, SMTP 25) |
| – | Registered Ports | Vendor and user applications registered with IANA (e.g., MySQL 3306, PostgreSQL 5432, RDP 3389) |
| – | Dynamic / Ephemeral Ports | Short-lived client source ports assigned automatically by the OS kernel for outbound sessions |
2. Multiplexing and Demultiplexing
- Multiplexing (Sender Side): The transport layer gathers data chunks from different application sockets, encapsulates each with a transport header containing source and destination port numbers, and passes the segments to the network layer.
- Demultiplexing (Receiver Side): The transport layer inspects the header fields of each incoming segment to deliver the payload to the matching socket:
- Connectionless Demultiplexing (UDP): Identified strictly by a 2-tuple:
(Destination IP, Destination Port). Segments from different source IPs/ports sent to the same destination port land in the same UDP socket. - Connection-Oriented Demultiplexing (TCP): Identified by a 4-tuple:
(Source IP, Source Port, Destination IP, Destination Port). Two clients connecting to the same web server port443receive separate TCP sockets because their source IP/port differs.
- Connectionless Demultiplexing (UDP): Identified strictly by a 2-tuple:
3. Segmentation and Reassembly
Applications transmit arbitrary volumes of data (such as a file). The transport layer partitions the stream into segments bounded by the Maximum Segment Size (MSS)—typically on standard Ethernet (). Each segment carries a sequence number so the receiver can detect gaps and reassemble bytes in the exact original order even if IP packets arrive out of order.
4. Error Control
Unlike the data link layer (hop-by-hop error control), transport-layer error control is end-to-end:
- Corruption Detection: Both TCP and UDP use a one's-complement checksum computed over a pseudo-header (Source IP, Destination IP, Protocol, Transport Length), the transport header, and the payload.
- Loss & Duplication Recovery (TCP): Uses sequence numbers, cumulative/selective acknowledgements (
ACK), retransmission timers (RTO), and duplicate-ACK detection to recover lost or reordered segments and discard duplicates.
5. Flow Control
Flow control prevents receiver buffer overrun:
- Uses a Sliding Window mechanism where the receiver advertises its remaining free buffer capacity in every segment's Receive Window (
rwnd) field. - The sender limits unacknowledged bytes in flight (
LastByteSent - LastByteAcked) to at mostrwnd. Ifrwnd = 0, the sender pauses transmission and sends periodic zero-window probes until buffer space reopens.
5.3 Transport protocols: TCP and UDP
User Datagram Protocol (UDP — RFC 768)
UDP is a minimalist, connectionless, message-oriented transport protocol. It adds only an fixed header consisting of four fields:
- Source Port (): Port of sending process (optional; if unused).
- Destination Port (): Port of receiving process.
- Length (): Total length of UDP header payload in bytes (minimum ).
- Checksum (): Covers pseudo-header, UDP header, and data (mandatory in IPv6; optional in IPv4).
Because UDP performs no handshake, maintains no connection state, and enforces no congestion control throttling, it offers low latency and predictable timing—critical for VoIP, DNS, DHCP, and live streaming.
Transmission Control Protocol (TCP — RFC 9293)
TCP is a connection-oriented, reliable, full-duplex, byte-stream transport protocol with a minimum header (up to with options):
- Key Header Fields:
Source Port(),Destination Port(),Sequence Number(),Acknowledgement Number(),Data Offset / Header Length(, in words),Control Flags(SYN,ACK,FIN,RST,PSH,URG,ECE,CWR),Window Size(),Checksum(),Urgent Pointer(), andOptions(e.g., MSS, Window Scale, SACK, Timestamps).
| Aspect | TCP (Transmission Control Protocol) | UDP (User Datagram Protocol) |
|---|---|---|
| Connection Model | Connection-oriented (3-way handshake) | Connectionless (no setup) |
| Reliability | Reliable (ACKs, timeouts, retransmissions) | Unreliable (best-effort delivery) |
| Ordering & Data Model | Ordered byte stream (no message boundaries) | Unordered discrete datagrams (preserves boundaries) |
| Header Overhead | – | Fixed |
| Flow & Congestion Control | Yes (rwnd sliding window + cwnd AIMD) | None at transport layer |
| Speed / Latency | Higher latency due to handshake and ACKs | Very low latency and overhead |
| Representative Uses | HTTP/HTTPS, SSH, FTP, SMTP, database queries | DNS, DHCP, SNMP, VoIP, online gaming |
5.4 TCP services: connection setup and release, reliable, stream oriented, flow-control, error-control
1. Connection Setup: Three-Way Handshake
Before exchanging application data, client and server synchronize initial sequence numbers (ISN) and negotiate options (such as MSS) in three steps:
- SYN: Client sends a segment with
SYN = 1,ACK = 0, and its random Initial Sequence Number . - SYN-ACK: Server allocates buffers/state and replies with
SYN = 1,ACK = 1, its own , and . - ACK: Client replies with
SYN = 0,ACK = 1, , and . Note that theSYNflag consumes phantom sequence number even with zero payload bytes.
2. Connection Release: Four-Way Handshake
Because TCP is full-duplex, each direction must be closed independently using the FIN flag (which also consumes sequence number):
- Host A finishes sending data and transmits
FIN = 1, Seq = u. - Host B replies
ACK = 1, Ack = u + 1(half-close: B may still send remaining data to A). - When Host B finishes sending, it transmits
FIN = 1, Seq = v. - Host A replies
ACK = 1, Ack = v + 1and enters theTIME_WAITstate (lasting , Maximum Segment Lifetime) so delayed duplicate packets expire and a lost finalACKcan be retransmitted cleanly.
3. Stream-Oriented Delivery
TCP treats application output as an unstructured stream of bytes, not discrete records. Every byte in the stream is numbered. If an application writes in two send() calls, TCP may transmit them as one segment or two segments, and the receiver may read them in a single recv() call.
4. Reliable Delivery, Error Control, and RTT Estimation
TCP achieves reliability over unreliable IP using:
- Cumulative Acknowledgements:
Ack = Nconfirms receipt of all bytes up to and expects byte next. - Retransmission Timeout (RTO): Dynamically adapted from measured
SampleRTTusing Jacobson/Karels' exponentially weighted moving average:
- Fast Retransmit: Receiving duplicate ACKs (4 identical ACKs in total) triggers immediate retransmission of the missing segment without waiting for RTO expiration.
5. Flow Control and Congestion Control Interaction
TCP maintains two windows simultaneously:
- Receiver Window (
rwnd): Protects the receiver's buffer (flow control). - Congestion Window (
cwnd): Protects intermediate network routers (congestion control) using Slow Start (exponential growth per RTT up tossthresh), Congestion Avoidance (linear AIMD additive increase per RTT), and Fast Recovery. - Effective sending window at any instant is:
5.5 Introduction to socket and socket programming
Network Socket
A socket is the software programming endpoint (API abstraction) between an application process and the OS kernel's transport protocol stack. Uniquely bound to an IP address, transport protocol (TCP or UDP), and port number, it exposes system calls (socket, bind, listen, accept, connect, send, recv, close) for network I/O.
Socket Types
- Stream Socket (
SOCK_STREAM): Uses TCP; provides reliable, full-duplex, ordered byte-stream connections. - Datagram Socket (
SOCK_DGRAM): Uses UDP; sends/receives connectionless individual packets (sendto/recvfrom) withoutlisten()oraccept().
TCP Client-Server Socket Lifecycle
- Server Setup:
socket()creates the listening descriptorbind()attaches(IP, Port)listen()marks it passive with a backlog queueaccept()blocks until a client completes the 3-way handshake and returns a new connected socket descriptor for that client. - Client Setup:
socket()creates the descriptorconnect()initiates the TCP 3-way handshake to the server's(IP, Port). - Data Exchange & Teardown: Both sides exchange bytes via
send()/recv()and terminate viaclose().
import socket
HOST = "127.0.0.1"
PORT = 9000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
server.bind((HOST, PORT))
server.listen(5)
conn, addr = server.accept()
with conn:
data = conn.recv(1024)
if data:
conn.sendall(data)Worked Out Examples
5.1
Host A initiates a TCP connection to Host B using an Initial Sequence Number , and Host B selects . After the 3-way handshake completes:
- Host A sends a segment carrying of data.
- Host B replies with a segment carrying of data, piggybacking its acknowledgement for Host A's first segment.
- Host A sends a second segment carrying of data, acknowledging Host B's data.
- Host B acknowledges Host A's second segment (with no data).
State the Seq number, Ack number, and active control flags (SYN, ACK) for all three handshake segments and the four subsequent data/ACK segments.
Tracing the Three-Way Handshake:
- Segment 1 (A B):
SYN = 1,Seq = 1000. (SYNconsumes sequence number.) - Segment 2 (B A):
SYN = 1, ACK = 1,Seq = 5000,Ack = 1000 + 1 = 1001. - Segment 3 (A B):
ACK = 1,Seq = 1001,Ack = 5000 + 1 = 5001.
Tracing Data Exchange and Cumulative Acknowledgements:
- Data 1 (A B, ):
ACK = 1,Seq = 1001(bytes –),Ack = 5001. - Data 2 (B A, ):
ACK = 1,Seq = 5001(bytes –),Ack = 1001 + 400 = 1401. - Data 3 (A B, ):
ACK = 1,Seq = 1401(bytes –),Ack = 5001 + 200 = 5201. - Final ACK (B A, ):
ACK = 1,Seq = 5201,Ack = 1401 + 600 = 2001.
- Handshake:
(SYN, Seq=1000)(SYN+ACK, Seq=5000, Ack=1001)(ACK, Seq=1001, Ack=5001). - Data 1 (A B):
Seq=1001,Ack=5001,ACK=1. - Data 2 (B A):
Seq=5001,Ack=1401,ACK=1. - Data 3 (A B):
Seq=1401,Ack=5201,ACK=1. - Final ACK (B A):
Seq=5201,Ack=2001,ACK=1.
5.2
A TCP connection operates over a link.
- If the round-trip time is , compute the Bandwidth-Delay Product (BDP) in bytes. Can a standard TCP receive window (max ) saturate this link?
- If the RTT increases to while the maximum window stays capped at (no Window Scaling option), compute the maximum achievable link utilization percentage.
- Suppose the sender's current and a new acknowledgement yields . Using , calculate the updated .
Calculating the Bandwidth-Delay Product at :
Since , a standard receive window is sufficient to keep the pipe full at RTT.
Calculating Link Utilization at : The sender can transmit at most per RTT.
(To achieve utilization at , the TCP Window Scale option from RFC 7323 is required because .)
Updating :
- ; yes, a window can fully saturate the link.
- Maximum link utilization at RTT is .
- Updated .
5.3
Suppose a UDP checksum calculation sums the following four hexadecimal words (representing pseudo-header, UDP header, and data): 0x8000, 0x9000, 0x0010, and 0x1234. Compute the one's-complement checksum in hexadecimal, and verify how the receiver confirms there were no bit errors.
Performing One's-Complement Addition with End-Around Carry:
- Add the first two words:
A carry-out of occurs in the bit. Wrapping the carry back into the least significant bit (end-around carry):
- Add the remaining two words (no further overflow):
Taking the One's Complement and Verifying at the Receiver: Invert every bit of 0x2245 (equivalently, subtract from 0xFFFF):
At the receiver, all four words plus the transmitted checksum 0xDDBA are summed using one's-complement addition:
Obtaining all (0xFFFF) confirms that no detected bit errors occurred in transit.
The UDP checksum is 0xDDBA. The receiver verifies integrity by summing all words including 0xDDBA and checking that the one's-complement sum equals 0xFFFF.
Practice Exercises
Practice Exercises — Transport Layer, TCP/UDP & Sockets
Explain the difference between connectionless (UDP) and connection-oriented (TCP) demultiplexing at a server host. Why can two clients simultaneously connect to port 80 on a web server without mixing their data?
Demultiplexing Tuple Structure:
- UDP Demultiplexing: Uses only the 2-tuple
(Destination IP, Destination Port). Every datagram arriving at a given UDP port is placed into the same single socket regardless of the sender's IP or source port. - TCP Demultiplexing: Uses the full 4-tuple
(Source IP, Source Port, Destination IP, Destination Port).
Separating Concurrent Web Clients: When Client 1 (10.0.0.5:51001) and Client 2 (10.0.0.8:51001 or even 10.0.0.5:51002) connect to server 192.0.2.10:80, the server's accept() call creates two distinct connected sockets distinguished by their unique 4-tuples, keeping the two streams completely isolated.
UDP demultiplexes using a 2-tuple (Dest IP, Dest Port), whereas TCP demultiplexes using a 4-tuple (Src IP, Src Port, Dest IP, Dest Port). Concurrent clients on port 80 have different source IPs and/or source ports, so the OS routes each client's segments to a separate TCP socket.
An application sends sensor readings over IPv4 (no IP or TCP options). Compare the transport-layer header overhead percentage (transport header divided by total transport segment size) when using UDP versus TCP.
Computing UDP Overhead:
- UDP header , payload , total UDP datagram .
Computing TCP Overhead:
- Minimum TCP header , payload , total TCP segment .
UDP transport header overhead is , whereas TCP transport header overhead is (double UDP's overhead for small messages).
Describe the purpose of the TIME_WAIT state during TCP connection termination, and explain why its duration is set to (Maximum Segment Lifetime).
Two Purposes of TIME_WAIT ():
- Reliable Final ACK Delivery: If the active closer's final
ACKto the passive closer'sFINis lost, the passive closer will time out and retransmit itsFIN. Staying inTIME_WAITallows the active closer to respond with anotherACKinstead of sending an erroneousRST. - Preventing Delayed Duplicate Interference: Waiting guarantees that any stray delayed packets from the old connection (and any responses to them) expire from the network before the same 4-tuple
(Src IP, Src Port, Dest IP, Dest Port)can be reused by a new TCP incarnation.
TIME_WAIT lasts so the active closer can re-acknowledge a retransmitted FIN if the final ACK was lost, and to ensure all delayed packets from the old connection expire before the 4-tuple is reused.
Before receiving a new acknowledgement, a TCP sender has and . A newly measured segment yields . Using and , compute the updated , , and Retransmission Timeout ().
Updating :
Updating and Computing :
Updated , , and .
List the sequence of socket system calls executed by a TCP server and a TCP client to establish a connection and exchange data, and explain why accept() returns a new socket descriptor rather than reusing the listening socket.
TCP Socket Call Sequences:
- TCP Server:
socket()bind()listen()accept()recv()/send()close(). - TCP Client:
socket()connect()send()/recv()close().
Role of the New Connected Socket: The original listening socket remains bound solely to listen for future incoming SYN requests from other clients. Returning a new connected descriptor bound to the specific client's 4-tuple allows the server (via threads, fork, or select/epoll) to handle multiple concurrent clients simultaneously on the same server port.
Server: socket -> bind -> listen -> accept -> recv/send -> close; Client: socket -> connect -> send/recv -> close. accept() returns a new connected socket so the original listening socket can continue accepting additional incoming client connections concurrently.