networking · intermediate · ~25 min

Final Project: HTTP status-line parser

Defensive text parsing of a structured one-liner.

Challenge

Implement int http_parse_status(const char *line, int *out_code, char *out_reason, size_t cap):

  • Line format: HTTP/1.x CODE REASON\r\n (the trailing CRLF is optional in the input).
  • Sets *out_code to the 3-digit integer.
  • Copies the reason phrase (without CRLF) into out_reason, NUL-terminated, truncated to cap-1 bytes.
  • Returns 1 on success, 0 on malformed.

Why this matters

HTTP is just text on a socket. Parsing the status line is the first step in writing a checker, a load balancer, or a service-monitoring tool. Real production HTTP libraries have made this mistake — RFC 7230 ambiguity is a known foot-gun.

Input format

A pointer to the status line (may not be NUL-terminated immediately — but our tests use NUL-terminated input).

Output format

See API.

Constraints

No allocations. cap >= 1.

Starter code

#include <stddef.h>
int http_parse_status(const char *line, int *out_code, char *out_reason, size_t cap) { /* TODO */ return 0; }

Common mistakes

Trusting sscanf (which won't handle the bounded reason copy); failing if there's no reason phrase (some servers emit none); confusing CR and LF.

Edge cases to handle

HTTP/1.0 or HTTP/1.1 both valid. Code must be 3 ASCII digits. Empty reason is allowed.

Complexity

O(line length).

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.