C Network Programming: BSD Sockets & TCP/UDP Server Architecture Masterclass
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.
#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;
} 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.