Network Programming
Build networked applications in C — socket programming, TCP/UDP communication, HTTP clients, and server architectures.
50 min•By Priygop Team•Last updated: Feb 2026
Socket Programming
- Socket Basics: socket() creates an endpoint, bind() assigns an address, listen() marks it as a passive socket, accept() accepts a connection, connect() connects to a server
- TCP Server: socket() → bind() → listen() → accept() → read()/write() → close(). Connection-oriented, reliable, ordered delivery. Used for HTTP, FTP, SSH
- TCP Client: socket() → connect() → read()/write() → close(). Connect to server's IP:port, exchange data bidirectionally
- UDP: socket(AF_INET, SOCK_DGRAM) → sendto()/recvfrom(). Connectionless, unreliable, unordered. Faster than TCP. Used for DNS, video streaming, online gaming
- select()/poll(): Multiplex multiple sockets — monitor multiple connections for readability/writability without threads. Foundation for event-driven servers
- epoll (Linux): Scalable I/O multiplexing — handles 100K+ concurrent connections efficiently. Used by nginx, Node.js, Redis. O(1) per event vs O(n) for select
Server Architectures
- Iterative: Handle one client at a time — simple but can't handle concurrent connections. Only for simple utility servers
- Fork-per-Connection: fork() a new process for each client — simple concurrency but expensive (process creation overhead). Traditional Unix approach
- Thread-per-Connection: pthread_create for each client — lighter than fork but still limited by thread count. Thousands of threads cause context switching overhead
- Event-Driven: Single thread using epoll/select — handles thousands of connections with callbacks. Non-blocking I/O. Highest performance, most complex to write
- Thread Pool + Event Loop: Combine event-driven I/O with worker thread pool — the modern high-performance server architecture. Used in production systems