Networking in C · advanced · ~15 min
Reply to a single HTTP request with a hard-coded response.
A toy HTTP server needs only a few steps:
127.0.0.1) so the server only accepts connections from your own machine.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.
This design serves exactly one connection. To handle multiple clients you need either:
fork per connection — start a new process for each client, orselect / poll multiplexing — watch many connections at once in a single process.Even an HTTP/1.0 toy server runs into genuine problems:
This is why production HTTP servers are far from trivial.
Content-Length header. Without it, the client cannot tell where the response body ends.\r\n line endings, with a blank line separating headers from the body.fork per connection or select/poll multiplexing.