Networking in C · advanced · ~15 min

Simple local HTTP server

Reply to a single HTTP request with a hard-coded response.

Lesson

The minimal flow

A toy HTTP server needs only a few steps:

  1. Bind to loopback (127.0.0.1) so the server only accepts connections from your own machine.
  2. Accept one connection from a client.
  3. Read the request the client sends.
  4. Write a fixed response, then close the connection.

The response is a single hard-coded HTTP message:

HTTP/1.0 200 OK\r\nContent-Length: 5\r\n\r\nhello

The \r\n sequences are carriage-return + line-feed, the line ending HTTP requires. A blank line (\r\n\r\n) separates the headers from the body. Here the body is hello, which is 5 bytes long.

Handling more than one client

This design serves exactly one connection. To handle multiple clients you need either:

  • fork per connection — start a new process for each client, or
  • select / poll multiplexing — watch many connections at once in a single process.

Why real servers are hard

Even an HTTP/1.0 toy server runs into genuine problems:

  • Framing — knowing where one message ends and the next begins.
  • Partial reads — data may arrive in pieces, not all at once.
  • Slow clients — a client that sends data slowly can tie up the server.

This is why production HTTP servers are far from trivial.

Common mistakes

  • Missing the Content-Length header. Without it, the client cannot tell where the response body ends.

Summary

  • A minimal server binds to loopback, accepts one connection, reads the request, writes a fixed response, and closes.
  • The response uses \r\n line endings, with a blank line separating headers from the body.
  • Serving multiple clients requires fork per connection or select/poll multiplexing.
  • Real servers must handle framing, partial reads, and slow clients, which makes them non-trivial.

Practice with these exercises