networking · intermediate · ~25 min
Defensive text parsing of a structured one-liner.
Pull the status code and reason phrase out of an HTTP response's first line — the first thing a health-checker or load balancer reads.
Implement int http_parse_status(const char *line, int *out_code, char *out_reason, size_t cap).
The status line has the form HTTP/1.x CODE REASON (a trailing \r\n is optional), e.g. HTTP/1.1 200 OK\r\n. Set *out_code to the 3-digit code and copy the reason phrase (without CRLF) into out_reason.
line: the NUL-terminated status line.out_code: receives the 3-digit status code as an int.out_reason, cap: output buffer for the reason phrase and its capacity (cap >= 1).Return 1 on success. Set *out_code to the integer code and copy the reason into out_reason, NUL-terminated and truncated to at most cap-1 bytes. Return 0 on malformed input (wrong version prefix, code not exactly 3 digits, missing spaces).
"HTTP/1.1 200 OK\r\n" -> 1, code=200, reason="OK"
"HTTP/1.0 404 Not Found" -> 1, code=404, reason="Not Found"
"HTTP/1.1 500 \r\n" -> 1, code=500, reason="" (empty reason allowed)
"garbage" -> 0
"HTTP/2.0 abc OK" -> 0 (code not 3 digits)
HTTP/1.0 and HTTP/1.1 are valid; the code must be exactly 3 ASCII digits.out_reason and never write past cap.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.
line, the NUL-terminated status line; out_code for the code; out_reason/cap for the reason phrase.
1 on success with *out_code set and out_reason filled (NUL-terminated, truncated to cap-1); 0 on malformed input.
No allocations; cap >= 1; version must be HTTP/1.0 or 1.1; code exactly 3 digits.
#include <stddef.h>
int http_parse_status(const char *line, int *out_code, char *out_reason, size_t cap) { /* TODO */ return 0; }
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.
HTTP/1.0 or HTTP/1.1 both valid. Code must be 3 ASCII digits. Empty reason is allowed.
O(line length).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.