C Network Programming: BSD Sockets & TCP/UDP Server Architecture Masterclass

โšก C (C17 / C23 Standard) ๐ŸŸข Lesson 63 ๐Ÿ“‚ Phase 22: System Programming & Embedded C ๐Ÿ“… 2026 Comprehensive Master Edition
๐Ÿ“Œ Covered in this in-depth guide: BSD Sockets API ยท TCP / IP Stack ยท Socket Lifecycle (socket bind listen accept) ยท Byte Order (htons htonl) ยท Concurrent TCP Server ยท Simple C HTTP Web Server

Welcome to Phase 22 (Chapter 63): C Network Programming โ€” BSD Sockets & TCP/UDP Server Architecture Masterclass! Network sockets allow programs to communicate over local networks and the internet. In this guide, you will master BSD Sockets, network byte order, and building a concurrent TCP web server in C.

1TCP Server Socket Lifecycle State Machine
TCP Server Socket Lifecycle: SERVER: CLIENT: socket() โ”€โ”€โ–บ Create socket handle socket() โ”€โ”€โ–บ Create socket handle bind() โ”€โ”€โ–บ Bind IP address & Port listen() โ”€โ”€โ–บ Mark as passive listener accept() โ”€โ”€โ–บ Block until connection โ—„โ”€โ”€โ”€โ”€ connect() โ”€โ”€โ–บ 3-Way TCP Handshake recv/send() โ—„โ”€โ”€โ”€โ”€โ”€โ”€ Full-Duplex Data Transfer โ”€โ”€โ”€โ”€โ”€โ”€โ–บ send/recv() close() โ”€โ”€โ–บ Terminate connection close() โ”€โ”€โ–บ Close socket
2Complete Concurrent C Web Server Project
C โ€” Minimal TCP HTTP Web Serverโ–ถ Run Code in C Compiler
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080
#define BUFFER_SIZE 1024

int main(void) {
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0) { perror("socket"); return 1; }

    int opt = 1;
    setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    struct sockaddr_in address;
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY; // Bind to all interfaces
    address.sin_port = htons(PORT);       // Host to Network Short

    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind"); return 1;
    }

    if (listen(server_fd, 10) < 0) { perror("listen"); return 1; }
    printf("HTTP Server running on http://localhost:%d ...\n", PORT);

    while (1) {
        int client_fd = accept(server_fd, NULL, NULL);
        if (client_fd < 0) continue;

        char buffer[BUFFER_SIZE] = {0};
        read(client_fd, buffer, sizeof(buffer) - 1);

        const char *http_response =
            "HTTP/1.1 200 OK\r\n"
            "Content-Type: text/html\r\n"
            "Connection: close\r\n\r\n"
            "<html><body><h1 style='color:#10b981'>Hello from C Web Server!</h1></body></html>";

        write(client_fd, http_response, strlen(http_response));
        close(client_fd);
    }
    close(server_fd);
    return 0;
}
3Technical FAQs

Q1: Why are htons() and htonl() necessary?

Network protocols transmit multi-byte integers in Big-Endian order. `htons()` converts Host byte order to Network byte order to ensure cross-platform compatibility.

Q2: What is the difference between TCP and UDP sockets?

TCP (`SOCK_STREAM`) is connection-oriented and reliable. UDP (`SOCK_DGRAM`) is connectionless, unacknowledged, and faster (used for gaming/streaming).

Q3: What does SO_REUSEADDR option do?

Prevents "Address already in use" errors during quick server restarts by allowing `bind()` to reuse local addresses in TIME_WAIT state.

Q4: How do high-performance servers handle thousands of concurrent connections?

Using I/O multiplexing system calls (`select`, `poll`, `epoll` on Linux, `kqueue` on BSD) instead of spawning 1 thread per socket.

Q5: What is the purpose of the listen() backlog argument?

Specifies the maximum queue length of pending un-accepted connections allowed in the kernel before new connections are rejected.