Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

xserv — HTTP Server in C

A basic HTTP server built from scratch in C with no external libraries. Part of my series building systems-level projects in C toward EduOS — a privacy-first, AI-native OS for African schools.

Features

  • TCP socket server listening on port 8080
  • Parses raw HTTP GET requests
  • Serves static HTML files from the working directory
  • Returns proper HTTP headers including Content-Type and Content-Length
  • Returns 404 for missing files
  • Handles concurrent clients by forking a child process per connection

How it works

1. TCP Server

Creates a socket, binds it to port 8080, and listens for incoming connections. Each connection is accepted in a loop and handed to a child process via fork().

2. HTTP Request Parsing

Reads the raw request bytes off the socket. Extracts the first line (e.g. GET /index.html HTTP/1.1) and uses strtok to pull out the requested file path.

3. File Serving

Opens the requested file relative to the working directory. Sends a proper HTTP response with Content-Type and Content-Length headers, followed by the file contents in chunks. Returns a 404 response if the file doesn't exist.

4. Concurrent Clients

After accept(), the server forks a child process to handle each client. The parent immediately loops back to accept the next connection. SIGCHLD is ignored so the OS auto-reaps finished children with no zombies.

Build

mkdir build && cd build
cmake ..
make

Run

./xserv

Place your HTML files in the working directory, then open:

http://localhost:8080/index.html

Project Structure

xserv/
├── main.c          # Full server implementation
├── index.html      # Sample static file
└── CMakeLists.txt

Key Concepts

  • socket() — creates a network endpoint
  • bind() — assigns the socket to an address and port
  • listen() — marks the socket as passive, ready to accept
  • accept() — blocks until a client connects, returns a new fd
  • fork() — spawns a child process per client for concurrency
  • fseek/ftell — gets file size for Content-Length header
  • SO_REUSEADDR — allows immediate port reuse after restart
  • SIGCHLD + SIG_IGN — auto-reaps child processes

Part of a larger journey

This is Project 13 in my C systems programming series. Previous projects include a memory allocator, file explorer, process monitor, and terminal text editor — all built from scratch.

About

A basic HTTP server written in C from scratch. Serves static files over TCP, parses HTTP GET requests, and handles concurrent clients with fork().

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages