networking · intermediate · ~15 min
Look up an HTTP header value.
HTTP headers are Name: value lines terminated by CRLF. Look up a header by name and copy its value.
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.
req: the full request (or header block) text.name: the header name to look up.out, outsz: destination buffer and its size.Returns the value length on success, or -1 if the header is not found.
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
-1.outsz and NUL-terminate.The request text (req), the header name to find (name), and an output buffer (out, outsz).
The value length on success, or -1 if the header is not present.
Match 'name: ', copy up to the next CR/LF, bound by outsz, NUL-terminate; return -1 if absent.
#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.