Transport layer services and socket programming
Transport layer provides process-to-process (end-to-end) communication: services such as reliable data transfer, multiplexing/demultiplexing, flow and congestion control, and the socket API used by applications to send/receive data over TCP/UDP.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Network engineers and systems programmers use the Transport layer when building applications that send data between programs on different machines. Understanding transport services (TCP, UDP) and the socket API is essential to implement reliable connections, design high-performance servers, debug network problems and answer exam questions in computer networks.
Key ideas
Port: A 16-bit number that identifies a specific process or service on a host. Well-known ports (0–1023) are reserved for common services. An ephemeral port is a short-lived port (assigned by the OS) used by a client. IANA ranges: registered 1024–49151, dynamic/private 49152–65535; OS-default ephemeral ranges vary but typically lie in the dynamic/private range.
Socket: An abstraction (programming interface) that represents an endpoint for communication. For TCP, a connection is identified by the 4-tuple (source IP, source port, destination IP, destination port); for UDP, a socket is identified by its local IP and port (a connected UDP socket also has a peer IP and port).
Multiplexing and demultiplexing: Multiplexing: combining data from multiple application processes into transport segments. Demultiplexing: delivering received segments to the correct application process using port numbers.
UDP (User Datagram Protocol): A connectionless transport protocol. Key properties: no connection setup, no guaranteed delivery, preserves message boundaries, provides a checksum for error detection, supports simple request–reply and streaming where loss is acceptable. Use when low overhead and low latency are more important than reliability.
TCP (Transmission Control Protocol): A connection-oriented, reliable, byte-stream transport protocol. Key services:
- Reliability: retransmission of lost segments using acknowledgements (ACKs) and timeouts.
- Ordered delivery: TCP reorders out-of-order segments before presenting bytes to the application.
- Flow control: receiver advertises a window (rwnd) that limits how much unacknowledged data sender may have outstanding; prevents receiver buffer overflow.
- Congestion control: algorithms (slow start, congestion avoidance, fast retransmit, fast recovery) to avoid sending too fast for the network.
Three-way handshake (connection establishment): A TCP connection is established by exchange of three segments: SYN, SYN+ACK, ACK. This synchronises sequence numbers and agrees on initial sequence numbers (ISNs).
Connection release: TCP uses a four-segment (or three, in some cases) close using FIN and ACK flags; either side can initiate close.
Checksum: A simple error-detection field in UDP and TCP headers computed over header, payload and a pseudo-header (source IP, destination IP, protocol, length). It detects common transmission errors. Note: the UDP checksum is optional in IPv4 but mandatory in IPv6.
Blocking vs non-blocking sockets: A blocking socket call (e.g., recv on a blocking socket) waits until data is available; a non-blocking call returns immediately if no data.
Socket API (Berkeley-style): Common POSIX functions to create and manage sockets: socket(), bind(), listen(), accept(), connect(), send(), recv(), sendto(), recvfrom(), close(), setsockopt(), getaddrinfo(), select(), poll(). These calls are the exam's expected syntax and semantics.
Diagrams to draw when asked:
- For TCP three-way handshake: draw two vertical lifelines labeled "Client" (left) and "Server" (right). Draw three horizontal arrows from client→server labeled "SYN, seq = x"; server→client labeled "SYN+ACK, seq = y, ack = x+1"; client→server labeled "ACK, seq = x+1, ack = y+1". Label ISNs and resulting established connection.
- For TCP sliding window: draw sender and receiver boxes, a timeline, show segments 1..N in flight up to window size, and ACKs returning, with rwnd value annotated.
Assumptions commonly used in derivations/exams:
- IP provides best-effort packet delivery (packets may be lost, duplicated, reordered).
- Underlying network MTU limits segment payload (commonly 1500 byte Ethernet MTU → TCP MSS often 1460 bytes after headers) — state and verify the typical MSS value if required. For IPv6, the typical MSS on Ethernet is about 1440 bytes (40-byte IPv6 header), and actual MSS may be lower due to options or tunneling overhead.
Formulas
For this programming-heavy topic, remember these syntax prototypes and short key relations.
- Socket creation (IPv4, TCP):
int sockfd = socket(AF_INET, SOCK_STREAM, 0);- AF_INET = IPv4, SOCK_STREAM = TCP.
- Socket creation (UDP):
int sockfd = socket(AF_INET, SOCK_DGRAM, 0); - Bind a socket:
int res = bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)); - Listen (server, TCP):
int res = listen(sockfd, backlog); - Accept (server, TCP):
int clientfd = accept(sockfd, (struct sockaddr*)&clientaddr, &addrlen); - Connect (client, TCP):
int res = connect(sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)); - Send/receive (stream):
ssize_t n = send(sockfd, buf, len, flags);ssize_t n = recv(sockfd, buf, len, flags); - Send/receive (datagram):
sendto(sockfd, buf, len, flags, (struct sockaddr*)&addr, addrlen);recvfrom(...) - Close socket:
close(sockfd); - Network byte order helpers:
uint16_t htons(uint16_t hostshort);uint32_t htonl(uint32_t hostlong);ntohs,ntohl.
Key transport performance relation (pipeline/window model):
Throughput_max = Window_size / RTT where
- Window_size in bytes, RTT in seconds; throughput in bytes/sec.
- Applies when sender is limited by window (no other bottlenecks). In TCP, use the effective Window_size = min(receiver window (rwnd), congestion window (cwnd)).
Unit conversions: 1 byte = 8 bits; 1 Mbps = 1,000,000 bits/s (use SI multiples unless the exam specifies mebibits).
Worked examples
Example 1 — TCP three-way handshake (step-by-step trace) Given: Client ISN = 1000, Server ISN = 3000. Steps:
- Client → Server: send SYN, seq = 1000.
- Server receives SYN, chooses its ISN = 3000, replies: SYN+ACK with seq = 3000, ack = 1001 (client ISN + 1).
- Client receives SYN+ACK and replies: ACK with seq = 1001, ack = 3001.
- Connection established. After this, the next byte the client will send has sequence number 1001, the server expects to receive next byte 1001 from the client, and the client expects to receive next byte 3001 from the server.
Diagram to draw: two vertical lines labeled Client and Server. Three arrows labeled as above with sequence and ack numbers.
Example 2 — UDP echo server (conceptual C sequence) Goal: Server listens on port 5000 and echoes messages back. Client sends "Hello". Server steps (conceptual):
- Create socket:
sockfd = socket(AF_INET, SOCK_DGRAM, 0); - bind() to port 5000 on INADDR_ANY.
- Loop:
n = recvfrom(sockfd, buf, sizeof(buf), 0, &cliaddr, &len);thensendto(sockfd, buf, n, 0, &cliaddr, len);. Client steps: sockfd = socket(AF_INET, SOCK_DGRAM, 0);- Fill server sockaddr_in with IP and port 5000.
sendto(sockfd, "Hello", 5, 0, &serveraddr, sizeof(serveraddr));n = recvfrom(sockfd, buf, sizeof(buf), 0, NULL, NULL);expect to receive "Hello".
Expected behaviour: server does not establish a connection; each request is a datagram. If server is down, client receives ICMP error or times out (implementation dependent).
Example 3 — Sliding-window throughput numeric
Given: Sender window = 64 KiB = 65536 bytes, RTT = 50 ms = 0.05 s.
Formula: Throughput = Window_size / RTT.
Compute:
Throughput = 65536 bytes / 0.05 s = 1,310,720 bytes/s.
Convert to bits/s: 1,310,720 * 8 = 10,485,760 bits/s = 10.48576 Mbps.
Final answer: 10.49 Mbps (approx).
Common mistakes
- Using
sendto/recvfromwith TCP sockets (these are for datagrams) or forgetting to call listen() before accept() in TCP server. - Not converting port and IP fields to network byte order (forgetting htons/htonl or ntohs/ntohl).
- Assuming UDP preserves message boundaries larger than the MTU; datagrams larger than path MTU are fragmented or dropped.
- Misunderstanding close(): calling close() on a TCP socket may block; using shutdown() is the proper way to half-close a connection.
- Misreading blocking behavior: accept(), recv() block by default — they do not return immediately unless set non-blocking. Also, assuming one recv()/send() transfers a complete application message on TCP is incorrect; TCP is a byte stream, so applications must loop to read/write until the desired byte count is transferred.
- Using the wrong socket domain (AF_INET vs AF_INET6) or mixing IPv4 addresses with AF_INET6 without mapped addresses.
For your exam
Typical question types:
- Definitions (e.g., define transport layer, socket, port).
- Short notes (compare TCP and UDP, explain socket API calls).
- Derivations (derive throughput = window/RTT and show how window and RTT affect throughput).
- Trace questions (TCP handshake, sequence numbers, ACKs, state transitions, sliding window example).
- Programs / pseudo-code (write a simple TCP iterative server or a UDP echo server; list steps and key calls).
- Diagrams (draw the three-way handshake timeline, TCP sliding-window pipeline).
What full-marks answers include:
- Precise definitions with bold terms and correct units where needed.
- Correct function prototypes and ordering for socket code (socket → bind → listen → accept for TCP server; socket → sendto/recvfrom for UDP).
- Proper handling of byte order and explicit use of htons/ntohs where ports/addresses appear.
- For numerical answers, show formula, substitute numbers with units, and final numeric answer with units.
Quick check
- What flag combination starts and acknowledges a TCP connection?
- Which socket call does a TCP server use to accept an incoming connection?
- Write the simple formula that gives max throughput when the sender is limited by the window and RTT.
Answers: 1) SYN then SYN+ACK then ACK (three-way handshake). 2) accept(). 3) Throughput = Window_size / RTT.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?