PadhaikoAll subjects

Socket Programming and Network APIs (part 1: 4.1–4.3)

Network and Systems Programming (ENCT 386)

Open in the Padhaiko app

4.1 Socket interface and API

A socket is the standard operating system abstraction for an endpoint of bidirectional inter-process communication across a network (or locally between processes on the same machine). In POSIX/Linux, every socket is represented by an ordinary file descriptor (int sockfd) in the process's FD table, allowing programs to use read()/write() (alongside specialized send()/recv()) and close().

Definition

BSD Socket and Communication Association

An internet socket is created via int socket(int domain, int type, int protocol); and uniquely identified across a network by a 5-tuple association: (protocol, local_IP, local_port, remote_IP, remote_port)

Socket Address Structures

Because socket calls accept multiple address families, POSIX defines a generic base pointer type struct sockaddr * and concrete family structs that cast cleanly to it:

Byte Ordering (Endianness) and Address Conversion

x86-64 and most ARM CPUs store multi-byte integers in Host Byte Order (Little-Endian)—least-significant byte at the lowest memory address—whereas all Internet protocols (IP, TCP, UDP) require Network Byte Order (Big-Endian)—most-significant byte first.

Byte-Order and IP Address Conversion Functions
FunctionHeaderPurpose
uint16_t htons(uint16_t host16)<arpa/inet.h>Convert 16-bit port from Host to Network byte order
uint32_t htonl(uint32_t host32)<arpa/inet.h>Convert 32-bit IPv4 address from Host to Network byte order
uint16_t ntohs(uint16_t net16)<arpa/inet.h>Convert 16-bit port from Network to Host byte order
uint32_t ntohl(uint32_t net32)<arpa/inet.h>Convert 32-bit IPv4 address from Network to Host byte order
inet_pton(AF_INET, "192.168.1.1", &addr)<arpa/inet.h>Presentation (ASCII string) to Numeric binary (IPv4 & IPv6 safe)
inet_ntop(AF_INET, &addr, buf, len)<arpa/inet.h>Numeric binary to ASCII string (thread-safe)
getaddrinfo(host, port, &hints, &res)<netdb.h>Protocol-independent DNS + service resolution (replaces gethostbyname)

4.2 TCP socket programming (Client-server model)

Transmission Control Protocol (TCP) provides a connection-oriented, reliable, full-duplex, ordered byte stream (SOCK_STREAM). Before any data flows, client and server complete a three-way handshake (SYN -> SYN-ACK -> ACK).

TCP Client-Server Socket LifecycleText
       TCP SERVER                                    TCP CLIENT
       ----------                                    ----------
  socket(AF_INET, SOCK_STREAM, 0)
       |
  setsockopt(SO_REUSEADDR)
       |
  bind(local IP + port)
       |
  listen(listen_fd, backlog)
       |
  accept()  <--- blocks until 3-way handshake ---  socket(AF_INET, SOCK_STREAM, 0)
       |         <==============================>  connect(server IP + port)
       |   (returns NEW conn_fd for this client)
       v                                                 |
  recv(conn_fd)  <======= TCP Byte Stream =======  send(sock_fd)
  send(conn_fd)  ======== TCP Byte Stream =======> recv(sock_fd)
       |                                                 |
  close(conn_fd) <------- FIN / ACK teardown ----> close(sock_fd)

Step-by-Step Semantics of TCP Socket Calls

  1. socket(): Creates an unbound, unconnected endpoint fd.
  2. setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)): Essential on servers so restarting a crashed/stopped server can immediately re-bind its port even while old connections sit in TIME_WAIT.
  3. bind(listen_fd, addr, addrlen): Associates the socket with a specific local IP (INADDR_ANY or interface IP) and port number (ports < 1024 require root/CAP_NET_BIND_SERVICE).
  4. listen(listen_fd, backlog): Marks the socket as passive (listening) and allocates two kernel queues: the SYN queue (incomplete half-open handshakes) and the Accept queue (completed connections waiting for accept(), bounded by backlog).
  5. accept(listen_fd, &cli_addr, &cli_len): Pops one completed connection from the Accept queue and returns a brand-new connected file descriptor (conn_fd). Crucially, listen_fd stays open solely to accept future clients, while conn_fd communicates exclusively with that single client.
  6. connect(sock_fd, srv_addr, len): Used by the client to initiate the TCP three-way handshake with the server's IP and port (kernel automatically assigns an ephemeral source port).
  7. send() / recv() and shutdown(): Transmit/receive bytes. Note that recv() returning 0 means the peer performed an orderly close (FIN). Calling shutdown(fd, SHUT_WR) sends FIN (half-close) while still allowing the caller to recv() remaining replies before calling close().

4.3 UDP socket programming

User Datagram Protocol (UDP) provides a connectionless, unreliable (best-effort), datagram-oriented transport (SOCK_DGRAM). There is no handshake (listen() and accept() are never used), no retransmission, and no congestion control—making UDP ideal for DNS queries, VoIP/video streaming, online gaming, DHCP, and QUIC.

UDP Client-Server Socket LifecycleText
       UDP SERVER                                    UDP CLIENT
       ----------                                    ----------
  socket(AF_INET, SOCK_DGRAM, 0)              socket(AF_INET, SOCK_DGRAM, 0)
       |                                                 |
  bind(local IP + port)                                  | (kernel auto-assigns
       |                                                 |  ephemeral port)
  recvfrom(sock_fd, buf, ..., &cli_addr) <== DGRAM == sendto(sock_fd, ..., srv_addr)
       |                                                 |
  sendto(sock_fd, reply, ..., &cli_addr) === DGRAM ==> recvfrom(sock_fd, ...)
       |                                                 |
  close(sock_fd)                                    close(sock_fd)

Key Properties of UDP Programming

AspectTCP (SOCK_STREAM)UDP (SOCK_DGRAM)
Connection SetupConnection-oriented (3-way handshake)Connectionless (zero handshake)
Reliability & OrderingGuaranteed delivery, in-order, automatic retryBest-effort; packets may drop, duplicate, or reorder
Message BoundariesNo (unstructured byte stream; needs framing)Yes (1 sendto() = 1 datagram)
Transport Header Size20 bytes (without options)8 bytes
Broadcast / MulticastUnicast only (1-to-1)Supports unicast, broadcast, and multicast
Typical ApplicationsHTTP/HTTPS, SSH, FTP, SMTP, databasesDNS, DHCP, VoIP, gaming, NTP, QUIC/HTTP3

Worked Examples

Example

Network Byte Order Encoding of IPv4 Address and Port

A server binds to IPv4 address 192.168.10.25 and port 8080 on an x86-64 (little-endian) Linux machine.

  1. Compute the big-endian (network byte order) hexadecimal bytes stored in memory for sin_port (htons(8080)) and sin_addr.s_addr (inet_pton / htonl).
  2. Compare those bytes with what a little-endian host integer 8080 looks like in RAM if a programmer forgets htons().

Converting Port 8080 to Hexadecimal and Big-Endian Bytes:

  • 8080 = 31 * 256 + 144 = 0x1F90.
  • In Network Byte Order (Big-Endian), the most-significant byte comes first in memory: [0x1F, 0x90] (lowest address holds 0x1F, next holds 0x90).
  • If the programmer forgets htons(8080) on little-endian x86-64, memory holds [0x90, 0x1F], which the network interprets as big-endian 0x901F = 36,895—causing the server to listen on port 36895 instead of 8080!

Converting IPv4 192.168.10.25 to Network Byte Order:

  • 192 = 0xC0, 168 = 0xA8, 10 = 0x0A, 25 = 0x19.
  • As a 32-bit big-endian integer: 0xC0A80A19 (3,232,238,105).
  • In memory (sin_addr.s_addr), bytes appear in order: [0xC0, 0xA8, 0x0A, 0x19].
Answer:
  1. sin_port (htons(8080)) stores bytes 1F 90; sin_addr stores C0 A8 0A 19 (0xC0A80A19).
  2. Forgetting htons(8080) stores little-endian 90 1F, binding port 36895 instead of 8080.
Example

Iterative TCP Echo Server and Client in C

Write a complete, compilable C implementation of an iterative IPv4 TCP echo server listening on port 9000 (with SO_REUSEADDR enabled) and a matching TCP client that sends "Hello TCP" and reads the reply.

Implement the TCP Echo Server (tcp_echo_srv.c):

Iterative TCP Echo Server (IPv4)C
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void) {
    int srv = socket(AF_INET, SOCK_STREAM, 0);
    int opt = 1;
    setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    struct sockaddr_in addr = {0};
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(9000);

    if (bind(srv, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); return 1; }
    if (listen(srv, 16) < 0) { perror("listen"); return 1; }

    while (1) {
        struct sockaddr_in cli;
        socklen_t clen = sizeof(cli);
        int conn = accept(srv, (struct sockaddr *)&cli, &clen);
        if (conn < 0) continue;

        char buf[1024];
        ssize_t n;
        while ((n = recv(conn, buf, sizeof(buf), 0)) > 0) {
            send(conn, buf, (size_t)n, 0);
        }
        close(conn);
    }
    close(srv);
    return 0;
}

Implement the Matching TCP Client (tcp_echo_cli.c):

TCP Echo Client (IPv4)C
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void) {
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in srv = {0};
    srv.sin_family = AF_INET;
    srv.sin_port = htons(9000);
    inet_pton(AF_INET, "127.0.0.1", &srv.sin_addr);

    if (connect(sock, (struct sockaddr *)&srv, sizeof(srv)) < 0) { perror("connect"); return 1; }

    const char *msg = "Hello TCP";
    send(sock, msg, strlen(msg), 0);

    char buf[1024];
    ssize_t n = recv(sock, buf, sizeof(buf) - 1, 0);
    if (n > 0) {
        buf[n] = '\0';
        printf("Echoed: %s\n", buf);
    }
    close(sock);
    return 0;
}
Answer:

The server creates SOCK_STREAM, sets SO_REUSEADDR, calls bind() and listen(), accepts each client onto a new conn fd, echoes bytes until recv() returns 0, and closes conn. The client connects via connect(), sends "Hello TCP", prints the echoed response, and closes sock.

Example

UDP Datagram Server and Client with Client Address Reply

Write a C UDP echo server on port 9001 and a UDP client using sendto() and recvfrom(), explaining why the server does not call listen() or accept().

Why UDP Skips listen() and accept(): UDP is connectionless—there is no 3-way handshake and no per-client kernel connection queue. One single SOCK_DGRAM socket receives datagrams from all clients.

Implement UDP Server and Client (udp_echo.c):

UDP Echo Server (Port 9001)C
#include <arpa/inet.h>
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void) {
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in srv = {0};
    srv.sin_family = AF_INET;
    srv.sin_addr.s_addr = htonl(INADDR_ANY);
    srv.sin_port = htons(9001);

    bind(fd, (struct sockaddr *)&srv, sizeof(srv));

    char buf[1500];
    while (1) {
        struct sockaddr_in cli;
        socklen_t clen = sizeof(cli);
        ssize_t n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&cli, &clen);
        if (n > 0) {
            sendto(fd, buf, (size_t)n, 0, (struct sockaddr *)&cli, clen);
        }
    }
    close(fd);
    return 0;
}
UDP Echo ClientC
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void) {
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in srv = {0};
    srv.sin_family = AF_INET;
    srv.sin_port = htons(9001);
    inet_pton(AF_INET, "127.0.0.1", &srv.sin_addr);

    const char *msg = "Hello UDP";
    sendto(fd, msg, strlen(msg), 0, (struct sockaddr *)&srv, sizeof(srv));

    char buf[1500];
    ssize_t n = recvfrom(fd, buf, sizeof(buf) - 1, 0, NULL, NULL);
    if (n > 0) {
        buf[n] = '\0';
        printf("UDP Reply: %s\n", buf);
    }
    close(fd);
    return 0;
}
Answer:

The UDP server binds port 9001 once, receives each datagram along with the sender's address via recvfrom(), and replies directly to &cli via sendto() without any listen() or accept() call.


Exercises

Practice Exercises — Socket Programming (Part 1)

Question 1

Explain the roles of socket(), bind(), listen(), accept(), and connect() in the TCP client-server model. Why does accept() return a brand-new file descriptor instead of reusing listen_fd?

Roles of the Five TCP Calls:

  • socket(): Allocates a kernel socket endpoint and returns its file descriptor.
  • bind(): Assigns a specific local IP address and port to the server socket.
  • listen(): Transitions the socket into passive listening mode and creates the SYN and Accept queues (sized via backlog).
  • accept(): Extracts a completed client connection from the Accept queue (blocking if empty) and returns a new connected fd.
  • connect(): Called by the client to initiate the TCP three-way handshake toward the server's IP and port.

Why accept() Returns a New Descriptor: A listening socket (listen_fd) has only a local IP/port and remains passively waiting for new incoming SYN requests from any client. Each accepted connection requires its own unique 5-tuple (TCP, local_IP, local_port, remote_IP, remote_port) and its own TCP send/receive buffers and sequence state—so accept() returns a dedicated conn_fd for that client while listen_fd keeps accepting more clients concurrently.

Answer:

socket() creates the endpoint, bind() attaches local IP/port, listen() enters passive mode, connect() initiates the client handshake, and accept() returns a new connected fd per client so each client gets an isolated 5-tuple and TCP state while listen_fd continues accepting incoming connections.

Question 2

Convert TCP port 4433 and IPv4 address 10.20.30.40 into Network Byte Order (Big-Endian) hexadecimal representation. If a buggy client sends port 4433 on a little-endian CPU without calling htons(), what decimal port number will the server actually observe?

Port 4433 Conversion:

  • 4433 = 17 * 256 + 81 = 0x1151.
  • Network Byte Order (Big-Endian) bytes: [0x11, 0x51].
  • Without htons() on little-endian x86-64, memory holds [0x51, 0x11], which the network reads as 0x5111 = 81 * 256 + 17 = 20,753.

IPv4 10.20.30.40 Conversion:

  • Octets in hex: 10 = 0x0A, 20 = 0x14, 30 = 0x1E, 40 = 0x28.
  • Network Byte Order 32-bit hex: 0x0A141E28 (169,090,600 decimal; bytes [0A, 14, 1E, 28]).
Answer:

Network byte order: port 4433 = 0x1151 (11 51), IP 10.20.30.40 = 0x0A141E28 (0A 14 1E 28). Omitting htons() on a little-endian host sends bytes 51 11, which decodes to port 20,753.

Question 3

Why does TCP require application-level message framing (e.g., length prefixing or newline delimiters) even though UDP does not? Also explain why SO_REUSEADDR is routinely set before bind() on TCP servers.

TCP Framing vs. UDP Datagram Preservation: TCP exposes a continuous byte stream: the kernel may coalesce multiple send() calls into one segment (Nagle's algorithm) or split one large send() across multiple packets, so recv() has no built-in knowledge of application message boundaries. UDP, by contrast, preserves 1-to-1 datagram boundaries (1 sendto() = 1 recvfrom()).

Why Servers Set SO_REUSEADDR: When a TCP server terminates first while clients are active, the socket enters the TIME_WAIT state (lasting 2 * MSL, typically 60 seconds) to drain delayed packets. Without SO_REUSEADDR, restarting the server immediately fails with bind(): Address already in use (EADDRINUSE). Setting SO_REUSEADDR allows bind() to re-bind the port while old connections remain in TIME_WAIT.

Answer:

TCP is an unstructured byte stream (coalescing or splitting writes), requiring length-prefix or delimiter framing, whereas UDP preserves datagram boundaries. SO_REUSEADDR permits immediate server restart and bind() even when previous connections are still sitting in TIME_WAIT.

Question 4

An application sends a 100 KiB (102,400 bytes) payload over Ethernet (MTU = 1500 bytes) using IPv4 (20-byte IP header, no options).

  1. Over TCP (20-byte TCP header -> MSS = 1460 bytes), how many full/partial TCP segments are transmitted, and what is the total IP + TCP header overhead in bytes?
  2. Over UDP (8-byte UDP header -> max payload = 1472 bytes per unfragmented datagram), how many datagrams are needed, and what is the total IP + UDP header overhead in bytes?

Part 1 — TCP Segmentation (MSS = 1500 - 20 - 20 = 1460 bytes):

  • 102,400 / 1460 = 70 full segments (70 * 1460 = 102,200 bytes) + 1 final partial segment (200 bytes) = 71 TCP segments.
  • Total IP + TCP headers = 71 * (20 + 20) = 71 * 40 = 2,840 bytes.

Part 2 — UDP Datagrams (Max Payload = 1500 - 20 - 8 = 1472 bytes):

  • 102,400 / 1472 = 69 full datagrams (69 * 1472 = 101,568 bytes) + 1 final datagram (832 bytes) = 70 UDP datagrams.
  • Total IP + UDP headers = 70 * (20 + 8) = 70 * 28 = 1,960 bytes.
Answer:
  1. TCP: 71 segments with 2,840 bytes of IP + TCP header overhead.
  2. UDP: 70 datagrams with 1,960 bytes of IP + UDP header overhead.
Question 5

What happens inside the kernel when a client calls connect() on a UDP (SOCK_DGRAM) socket? List three practical benefits of connected UDP over unconnected UDP (sendto() / recvfrom()).

Kernel Behaviour of connect() on UDP: Unlike TCP, calling connect() on a UDP socket transmits zero packets (no handshake). Instead, the kernel simply stores the remote IP and port inside the socket's kernel PCB.

Three Practical Benefits of Connected UDP:

  1. Simpler I/O Calls: The application can call send() / write() and recv() / read() without passing struct sockaddr * on every packet.
  2. Asynchronous ICMP Error Delivery: If no process is listening on the target server port and the host replies with ICMP Port Unreachable, an unconnected UDP socket drops the error, whereas a connected UDP socket receives ECONNREFUSED on its next recv()/send().
  3. Kernel Peer Filtering & Routing Cache: The kernel discards datagrams arriving from any other IP/port and caches the routing lookup for slightly higher throughput.
Answer:

Calling connect() on a UDP socket performs no handshake; it binds the peer IP/port inside the kernel socket structure. Benefits: (1) allows send()/recv() without passing destination addresses repeatedly, (2) delivers ICMP Port Unreachable errors as ECONNREFUSED, and (3) filters out packets from unexpected peers while caching route lookups.

← Threads and Concurrent ProgrammingSocket Programming and Network APIs (part 2: 4.4–4.6) →