Skip to content
systemcoding.dev
Networking

Write a Simple HTTP/1.1 Server in C

Build a small HTTP/1.1 server in C with POSIX sockets: parse the request line, send correct headers and Content-Length, and handle keep-alive and bad requests.

7 min read
Summarize in AI
Flat illustration of network packets crossing between two hosts, with the C, Linux and Rust logos.

HTTP/1.1 is a text protocol, which makes it the friendliest first protocol to implement by hand. A server that answers one request correctly is about a hundred lines of C, and writing it teaches you the parts of sockets and parsing that every larger server also needs. This post builds one on Linux 6.12 with glibc 2.40 and C17: it listens, reads a request, parses the request line, and replies with proper status, headers and body. It then covers the two things beginners skip, which are a bad request and a connection that carries more than one request. The behaviour follows RFC 9112, the HTTP/1.1 message syntax specification.

What a request and a response look like

A request is a start line, header fields, an empty line, and an optional body. Every line ends in a carriage return followed by a line feed, which this post calls CRLF. The start line holds a method, a target and a version:

Text
GET /hello HTTP/1.1
Host: localhost:8080
User-Agent: curl/8.10.1
Accept: */*

The response mirrors it: a status line, headers, an empty line, a body. The two headers a simple server must get right are Content-Length, which says how many body bytes follow, and Content-Type. If the length is wrong, the client either waits forever for bytes that never come or reads the next response as part of this one.

Text
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 14
Connection: close

Hello, world!

The body there is Hello, world! plus a newline, which is 14 bytes. Count your bytes with strlen, never by eye.

The listening socket

A TCP server follows the same five calls every time: socket, setsockopt, bind, listen, accept. Setting SO_REUSEADDR before bind lets you restart the server immediately instead of waiting for the old socket's TIME_WAIT entries to expire.

server.cc
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

static int make_listener(unsigned short port)
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0)
        return -1;

    int yes = 1;
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes);

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    addr.sin_port = htons(port);

    if (bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0 ||
        listen(fd, 16) < 0) {
        close(fd);
        return -1;
    }
    return fd;
}

void handle_client(int client);

int main(void)
{
    int listener = make_listener(8080);
    if (listener < 0) {
        perror("listener");
        return 1;
    }
    puts("listening on 127.0.0.1:8080");

    for (;;) {
        int client = accept(listener, NULL, NULL);
        if (client < 0) {
            if (errno == EINTR)
                continue;
            perror("accept");
            break;
        }
        handle_client(client);
        close(client);
    }
    close(listener);
    return 0;
}
Text
listening on 127.0.0.1:8080

Binding to INADDR_LOOPBACK keeps the toy server off the network. Change it to INADDR_ANY only when you mean to expose it, because this code has no limits and no timeouts.

Read the request until the blank line

TCP is a byte stream, not a message stream, so one recv may return half a request or two requests. The header block ends at the first blank line, which is two CRLF pairs in a row. Read into a buffer in a loop until you find that sequence, and refuse requests that do not fit.

request.cc
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>

#define MAX_REQUEST 8192

/* Returns bytes read (header block complete), 0 on EOF, -1 on error or overflow. */
ssize_t read_head(int fd, char *buf, size_t cap)
{
    size_t used = 0;

    while (used < cap - 1) {
        ssize_t n = recv(fd, buf + used, cap - 1 - used, 0);
        if (n < 0)
            return -1;
        if (n == 0)
            return 0;
        used += (size_t)n;
        buf[used] = '\0';
        if (strstr(buf, "\r\n\r\n"))
            return (ssize_t)used;
    }
    return -1;
}

The cap matters. An unbounded read lets one client send endless header bytes and exhaust memory, so the function gives up at 8192 bytes. RFC 9112 recommends a server answer an overlong request line with 414 and keep limits on header size.

Parse the request line and answer

The request line has three tokens separated by single spaces. Use sscanf with width limits so a long token cannot overflow the destination arrays, and check that it found all three.

handler.cc
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

#define MAX_REQUEST 8192
ssize_t read_head(int fd, char *buf, size_t cap);

static void send_response(int fd, int status, const char *reason,
                          const char *type, const char *body)
{
    char head[256];
    size_t body_len = strlen(body);
    int n = snprintf(head, sizeof head,
                     "HTTP/1.1 %d %s\r\n"
                     "Content-Type: %s\r\n"
                     "Content-Length: %zu\r\n"
                     "Connection: close\r\n"
                     "\r\n",
                     status, reason, type, body_len);
    send(fd, head, (size_t)n, 0);
    send(fd, body, body_len, 0);
}

void handle_client(int client)
{
    char buf[MAX_REQUEST];
    if (read_head(client, buf, sizeof buf) <= 0)
        return;

    char method[8], target[256], version[16];
    if (sscanf(buf, "%7s %255s %15s", method, target, version) != 3) {
        send_response(client, 400, "Bad Request", "text/plain", "bad request\n");
        return;
    }
    if (strcmp(version, "HTTP/1.1") != 0 && strcmp(version, "HTTP/1.0") != 0) {
        send_response(client, 505, "HTTP Version Not Supported",
                      "text/plain", "version not supported\n");
        return;
    }
    if (strcmp(method, "GET") != 0) {
        send_response(client, 405, "Method Not Allowed", "text/plain",
                      "only GET is supported\n");
        return;
    }
    if (strcmp(target, "/hello") == 0)
        send_response(client, 200, "OK", "text/plain", "Hello, world!\n");
    else
        send_response(client, 404, "Not Found", "text/plain", "not found\n");
}

The output a client sees, using curl -i http://127.0.0.1:8080/hello, is:

Text
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 14
Connection: close

Hello, world!

And for a path that does not exist:

Text
HTTP/1.1 404 Not Found
Content-Type: text/plain
Content-Length: 10
Connection: close

not found

Connection: close tells the client the server will close the socket after this response, which is what handle_client followed by close(client) does. That is the simplest correct behaviour: HTTP/1.1 defaults to persistent connections, so a server that closes must say so. Leave the header out and a client may try to send a second request on a socket you already shut.

Two mistakes this version avoids

Sending a status without the right framing. A response with a body needs Content-Length or chunked encoding. Here the length is computed with strlen from the same string that is sent, so the two cannot disagree.

Trusting the input. The sscanf widths (%7s, %255s, %15s) are one less than the destination sizes, leaving room for the terminating zero. A request line with a 2,000-character target is truncated rather than written past the array, and then fails the route match. Truncation is safe, but a stricter server would answer 414 URI Too Long instead of matching a clipped path.

Reading a request body

Everything above handles requests with no body. A POST or PUT carries one, and the header block says how big it is with Content-Length. The rule from RFC 9112 is that the body is exactly that many bytes after the blank line, so after finding the end of the headers you may already hold part of the body in your buffer, because recv does not stop at the header boundary. The correct sequence is to compute how many body bytes you have already read, subtract that from the declared length, and keep calling recv for the remainder.

Two limits are non-negotiable here. First, parse the declared length with strtoul, check errno and the end pointer, and refuse a value above a cap you choose. Taking atoi on an attacker's header and then calling malloc with the result is how a server dies to a single request. Second, treat a request that has both Content-Length and Transfer-Encoding: chunked as an error. RFC 9112 calls that combination a request smuggling risk and tells servers to reject it or to ignore the length, so a toy server should simply answer 400.

Testing it without a browser

You do not need a browser to test any of this. curl shows the exchange, and a plain TCP client such as nc lets you send malformed requests by hand, which is where a parser earns its keep. Try a request line with only two tokens, one with a method longer than seven characters, and one that never sends the blank line. The first should get a 400, the second should be cut off by the %7s width and fail the method check, and the third should hit the 8192-byte cap or wait for more bytes.

That third case exposes the biggest gap in this server: a client that connects and sends nothing holds the single worker forever. Fix it before anything else if you ever extend this. Set a receive timeout with setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, ...) so recv returns EAGAIN after a few seconds, and treat that as a closed connection. A timeout of this kind is the cheapest defence against slow clients, and it turns a denial of service from one connection into a limit you control.

What it leaves out

It handles one client at a time, so a slow client blocks everyone. The next steps are a process or thread per connection, then an event loop with non-blocking sockets. It sends no Date header, which RFC 9110 says an origin server with a clock should send. It ignores Host, which HTTP/1.1 requires clients to send and servers to reject with 400 when missing. It does not serve files, so there is no path-traversal risk yet, but the moment you map targets to files you must reject any path containing .. and resolve it against a fixed root.

Share

Keep reading

Flat illustration of a microcontroller wired to an LED and a sensor, with the Bluetooth, Nordic Semiconductor and Arm logos.
Embedded

Create a Custom BLE GATT Service on nRF52

Define a custom 128-bit GATT service on nRF52 with Zephyr: characteristic properties, read and write callbacks, notifications through the CCC and MTU limits.

9 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.