networking · intermediate · ~15 min

Find a header value

Look up an HTTP header value.

Challenge

HTTP headers are Name: value lines terminated by CRLF. Look up a header by name and copy its value.

Task

Implement int header_value(const char *req, const char *name, char *out, int outsz) that finds the line name: value in req and copies the value part (everything after ": ", up to the next CR or LF) into out.

Input

  • req: the full request (or header block) text.
  • name: the header name to look up.
  • out, outsz: destination buffer and its size.

Output

Returns the value length on success, or -1 if the header is not found.

Example

req = "GET / HTTP/1.1\r\nHost: example.com\r\nAccept: */*\r\n\r\n"
header_value(req, "Host", out, 64)     ->   11, out="example.com"
header_value(req, "Cookie", out, 64)   ->   -1

Edge cases

  • Header absent: return -1.
  • Stop copying the value at the terminating CR or LF; bound by outsz and NUL-terminate.

Input format

The request text (req), the header name to find (name), and an output buffer (out, outsz).

Output format

The value length on success, or -1 if the header is not present.

Constraints

Match 'name: ', copy up to the next CR/LF, bound by outsz, NUL-terminate; return -1 if absent.

Starter code

#include <string.h>

int header_value(const char *req, const char *name, char *out, int outsz) {
    /* TODO */
    return -1;
}

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