networking · intermediate · ~15 min

Parse an HTTP status line

Robust string parsing, fail-fast on malformed input.

Challenge

Pull the numeric status code out of an HTTP status line, rejecting anything malformed.

Task

Implement int parse_status_line(const char *line, int *out_status) that parses a status line such as HTTP/1.1 200 OK\r\n and writes the 3-digit status code into *out_status. No main — the grader calls it. This is a pure parser; there is no network call.

Input

  • line: a candidate HTTP status line (NUL-terminated).
  • out_status: pointer that receives the parsed status code.

Output

Returns 0 and sets *out_status on success; returns -1 on malformed input (and leaves the status unset).

Example

"HTTP/1.1 200 OK\r\n"             ->   0, *out_status = 200
"HTTP/1.0 404 Not Found\r\n"      ->   0, *out_status = 404
"FOO/1.1 200 OK\r\n"             ->   -1
"HTTP/1.1 abc OK\r\n"            ->   -1

Edge cases

  • Missing or non-numeric status code returns -1.
  • A line not starting with HTTP/ returns -1.

Rules

  • Require the HTTP/ prefix, then exactly three decimal digits after the first space.

Input format

A candidate status line and an out_status pointer.

Output format

0 with *out_status set on success; -1 on malformed input.

Constraints

Require the HTTP/ prefix and exactly three decimal digits; pure parser.

Starter code

#include <stddef.h>

int parse_status_line(const char *line, int *out_status) {
    /* TODO */
    return -1;
}

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