Skip to content

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

http-server

A minimal, single-threaded HTTP server written from scratch in C for Linux.

Built with raw POSIX sockets — no external libraries, no frameworks. Just gcc and the standard library. It serves static files from the public/ directory over HTTP/1.1.

Features

  • Serves static files from public/
  • GET requests only (405 Method Not Allowed for anything else)
  • MIME type detection (currently HTML and plain text)
  • Custom 404 error page
  • Query string stripping (/page?foo=bar/page)
  • Request logging with client IP, port, status code, and bytes sent
  • Socket reuse via SO_REUSEADDR for quick restarts
  • 400 Bad Request handling for malformed request lines

Getting Started

Requirements

  • Linux
  • GCC (or any C99 compiler)
  • Make (optional)

Build

gcc -o http-server src/server.c

Or use make:

make

Run

./http-server

The server starts on port 8000 and serves files from public/:

[*] Server running on http://localhost:8000
[*] Press Ctrl+C to stop

Test it

curl http://localhost:8000/            # serves public/index.html
curl http://localhost:8000/anything-else  # serves public/anything-else or 404

Or open http://localhost:8000 in your browser.

Project Structure

├── http-server        # compiled binary
├── public/            # static files served by the server
│   └── index.html
└── src/
    └── server.c       # the entire server implementation

How It Works

  1. socket() creates a TCP socket, setsockopt() enables address reuse, and bind() + listen() start the server on port 8000.
  2. The main loop accepts one connection at a time and reads the request line.
  3. check_method() rejects anything that isn't GET with a 405.
  4. serve_file() maps the URL path to a file under public/ and reads it into memory.
  5. send_response() writes the HTTP/1.1 response headers followed by the body.
  6. log_request() prints an access log line like:
[12:34:56] 127.0.0.1:52734 "GET / HTTP/1.1" 200 223

Roadmap / Limitations

  • Single-threaded: handles one request at a time
  • No persistent connections (Connection: close always)
  • Limited MIME type coverage
  • No HTTP parsing beyond the request line (no headers, no bodies)
  • No directory traversal protection
  • No config for the port or document root

License

MIT

About

A lightweight, single-threaded HTTP server implemented in pure C that serves static files from a public directory. This project demonstrates fundamental socket programming and HTTP protocol implementation without external dependencies.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages