Skip to main content
Be Bitwise
CNetworking in C

Part ofSystems Programming Companion, week 12

Building a TCP Server

A TCP server sits and waits for clients to come knocking. The server side carries more ceremony than the client: create, bind, listen, accept, handle, close.

The Server Lifecycle

c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main() {
// 1. Create socket
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) { perror("socket"); return 1; }
// 2. Allow port reuse (avoids "Address already in use")
int opt = 1;
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
// 3. Bind to address
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = INADDR_ANY; // listen on all interfaces
if (bind(server_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind"); // e.g. port already taken
return 1;
}
// 4. Listen for connections
if (listen(server_fd, 5) < 0) { // backlog of 5
perror("listen");
return 1;
}
printf("Server listening on port 8080\n");
// 5. Accept and handle connections
while (1) {
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
if (client_fd < 0) {
perror("accept"); // one failed client shouldn't stop the server
continue;
}
char buffer[1024];
ssize_t bytes = recv(client_fd, buffer, sizeof(buffer) - 1, 0);
if (bytes > 0) {
buffer[bytes] = '\0';
printf("Received: %s\n", buffer);
const char *response = "Message received!";
send(client_fd, response, strlen(response), 0);
}
close(client_fd);
}
close(server_fd);
return 0;
}

Understanding Each Step

Bind ties the socket to an address and port. INADDR_ANY says you'll take connections on any interface the box has.

Listen flips the socket into passive mode, ready to accept rather than initiate. The backlog argument caps how many pending connections can queue up before the kernel starts dropping them.

Accept blocks until a client shows up. When one does, you get back a brand new file descriptor for that specific connection. The original listening socket keeps doing its job.

Key Concept

accept() returns a new socket for each client. The listening socket and the connected socket are separate file descriptors. This is what allows a server to handle multiple clients - each gets its own socket.

The Problem with Blocking

This server handles exactly one client at a time. While it's chatting with one, every other connection is parked in the queue. The odd part is that the second client can't tell. Its connect() succeeds straight away, because the kernel completes the handshake and files the connection in the backlog without asking the program:

Client B's request has been sitting in a kernel buffer the whole time. Nothing reads it until the loop comes back round to accept(). Real servers escape the bottleneck with:

  • fork() - spawn a child process per connection
  • Threads - pthread_create() per connection
  • I/O multiplexing - select(), poll(), or epoll() to handle many connections in one thread

A Forking Server

c
#include <signal.h>
// Before the loop: tell the kernel we'll never wait() for children,
// so finished ones are reaped automatically instead of becoming zombies.
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
sa.sa_flags = SA_NOCLDWAIT;
sigaction(SIGCHLD, &sa, NULL);
while (1) {
int client_fd = accept(server_fd, NULL, NULL);
if (client_fd < 0) {
perror("accept");
continue;
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
close(client_fd);
} else if (pid == 0) {
// Child process: handle this client
close(server_fd);
handle_client(client_fd);
close(client_fd);
_exit(0);
} else {
// Parent: close the client socket and continue accepting
close(client_fd);
}
}

fork() clones the process. The child takes the client; the parent slips back to accept() for the next one.

The sigaction call at the top matters. When a child exits, the kernel keeps a small record of it (its exit status) until the parent collects it with wait() or waitpid(). A parent that never does leaves a zombie for every finished client, and a busy server eventually runs out of process slots. Ignoring SIGCHLD with SA_NOCLDWAIT tells the kernel to discard those records. If you need the exit statuses, install a SIGCHLD handler that loops waitpid(-1, NULL, WNOHANG) instead.

Challenge: One Process, Many Clients

Forking works, but each client costs a whole process. Rewrite the iterative server so a single process serves several clients at once using poll(), with no fork() and no threads. Have it echo back whatever each client sends. To test it on your own machine, open two terminals, run nc localhost 8080 in each and type into both: neither should have to wait for the other.

Hint

Keep an array of struct pollfd. Slot 0 holds server_fd with events = POLLIN, and each accepted client gets a slot of its own. Every trip round the loop, call poll() and look at revents. POLLIN on the listening socket means accept() won't block, so accept and append the new descriptor. POLLIN on a client means recv() won't block; if it returns 0 the client has hung up, so close() it and remove its slot. select() follows the same pattern with fd_sets, but you have to rebuild the sets before every call and it can't watch descriptors numbered FD_SETSIZE (usually 1024) or higher.