Skip to main content
Be Bitwise
CNetworking in C

HTTP from Scratch

HTTP is text wrapped in TCP. Once you've parsed and built a few HTTP messages by hand in C, every web framework you'll ever use stops feeling magical.

HTTP Request Format

An HTTP request is plain text with a specific structure:

c
GET /index.html HTTP/1.1\r\n
Host: example.com\r\n
\r\n
  • Request line: method, path, and HTTP version
  • Headers: key-value pairs, each ending with \r\n
  • Empty line: signals the end of headers

On the wire there's nothing more to it than ASCII. Here's the shortest possible request line, GET / HTTP/1.1, as the bytes your recv() buffer would hold. Hover each field: the method is 47 45 54, the separators are plain spaces (20), and the line ends in 0d 0a, the \r\n your parser splits on.

Network Packet Builder

16 bytes
Hex Dump
474554202f20485454502f312e310d0a

Click a layer to expand fields. Hover a field to highlight its bytes.

Run your server and hit it with curl -v http://localhost:8080/. The lines curl prints after > are exactly these bytes, followed by the headers and the blank line.

Parsing a Request Line

c
#include <stdio.h>
#include <string.h>
void parse_request(const char *request) {
char method[16], path[256], version[16];
// Widths are buffer size minus one: a bare %s would overflow on a long request
if (sscanf(request, "%15s %255s %15s", method, path, version) != 3) {
printf("Malformed request line\n");
return;
}
printf("Method: %s\n", method);
printf("Path: %s\n", path);
printf("Version: %s\n", version);
}

Building an HTTP Response

c
const char *status_text(int code) {
switch (code) {
case 200: return "OK";
case 404: return "Not Found";
case 500: return "Internal Server Error";
default: return "Unknown";
}
}
void send_response(int client_fd, int status, const char *body) {
char response[4096];
int body_len = strlen(body);
snprintf(response, sizeof(response),
"HTTP/1.1 %d %s\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"Connection: close\r\n"
"\r\n"
"%s",
status, status_text(status), body_len, body
);
send(client_fd, response, strlen(response), 0);
}
Key Concept

HTTP relies on Content-Length to tell the receiver how many bytes of body data to expect. Without it, the client would not know when the response is complete. This is the same "how much data?" problem you solved with the recv() loop.

A Minimal HTTP Server

Combining what we learned about TCP servers with HTTP parsing:

c
void handle_http_client(int client_fd) {
char buffer[4096];
size_t total = 0;
buffer[0] = '\0';
// Keep reading until the blank line that ends the headers
while (strstr(buffer, "\r\n\r\n") == NULL) {
if (total == sizeof(buffer) - 1) return; // headers too big: give up
ssize_t n = recv(client_fd, buffer + total, sizeof(buffer) - 1 - total, 0);
if (n <= 0) return; // error, or client hung up
total += (size_t)n;
buffer[total] = '\0';
}
char method[16], path[256];
if (sscanf(buffer, "%15s %255s", method, path) != 2) return;
if (strcmp(path, "/") == 0) {
send_response(client_fd, 200, "Welcome to the server!");
} else if (strcmp(path, "/time") == 0) {
time_t now = time(NULL); // needs #include <time.h>
char *timestr = ctime(&now);
send_response(client_fd, 200, timestr);
} else {
send_response(client_fd, 404, "Not Found");
}
}

That's a real HTTP server, if a trusting one. It keeps calling recv until it has seen the \r\n\r\n that ends the headers, because a slow client can deliver a request in several pieces, and it refuses requests whose headers won't fit in the buffer. It ignores any body, which is fine for GET. Aim Chrome at it and you'll see the response render. Express, Django, Rails — they're all doing exactly this, buried under several floors of abstraction.

Status Codes

CodeMeaning
200OK
301Moved Permanently
404Not Found
500Internal Server Error

Picking the right code is mostly about the path. The runner below is the routing half of a static file server with no sockets in sight: it maps a request line to a status and a Content-Type, and refuses any path that tries to climb out of the web root with ... Predict the status for each test request before you run it.

Try itAdd a 405 for any method other than GET, and a .png entry to the type table.
C (GCC 9.2.0)

/notes..txt gets a 404, not a 403: two dots inside a file name are harmless, and only a whole .. segment moves up a directory. Real servers go further and resolve the path (or check it against the canonical web root) after URL-decoding, because %2e%2e is also ...

What We Have Built

Four lessons in, you've gone from raw socket() to a working HTTP server. The takeaway worth carrying forward: network protocols are just structured text sent over TCP. No magic anywhere — only conventions about which bytes go where, and when.

Challenges

Parse an HTTP response status line and print the status code.

C (GCC 9.2.0)