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;
}

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