Systems programming

Web server in C

A small multi-threaded HTTP server written from scratch in C that serves a folder of static files: pages, images, audio and video.

What it does

Start it in a folder and it serves that folder on port 8080. A request for / gets index.html, any other path gets the file of that name, and a missing file gets a 404 page. Paths with two dots (..), absolute paths and anything that is not a regular file also get a 404, so it never serves a file from outside its folder. The Content-Type header is set from the file extension: .html, .css, .js, .jpg, .png, .mp3 and .mp4. Every request is logged to the console.

How it works

The server opens a TCP socket with SO_REUSEADDR, so it can be restarted at once without waiting for the operating system to release the port, then binds, listens and accepts connections in a loop.

Each connection is handed to a new detached POSIX thread, so one slow client does not hold up the others. The thread reads the request line, finds the file, takes its size with fstat(), writes the response headers, and sends the body with sendfile().

sendfile() asks the kernel to copy the file straight from disk to the network socket. The bytes never pass through a buffer in the program, which saves copying and system calls compared with reading and writing in a loop.

More projects