networking · intermediate · ~15 min

Parse the status code

Extract the status code from a response.

Challenge

Pull the numeric status code out of an HTTP response's first line.

Task

Implement int parse_status_code(const char *resp) that returns the status code from a status line like HTTP/1.1 200 OK.

Input

  • resp: a NUL-terminated response string beginning with a status line.

Output

Return the integer status code (the token after the first space). Return -1 if resp does not start with HTTP/ or has no space.

Example

"HTTP/1.1 200 OK\r\n"      ->  200
"HTTP/1.0 404 Not Found"    ->  404
"garbage"                   ->  -1

Input format

resp: a NUL-terminated response string starting with the status line.

Output format

The integer status code, or -1 if resp doesn't start with HTTP/ (or has no space).

Constraints

Verify the HTTP/ prefix; the code is the token after the first space.

Starter code

#include <string.h>
#include <stdlib.h>

int parse_status_code(const char *resp) {
    /* TODO */
    return -1;
}

Common mistakes

Assuming read/write transmits all requested bytes at once; ignoring socket file descriptor cleanup; unhandled endianness conversions.

Edge cases to handle

Short reads/writes; peer closing socket (recv returns 0); signal interruption (EINTR); non-blocking EAGAIN.

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