networking · intermediate · ~20 min

Parse a Cookie header into name/value pairs

Strict header-parsing pattern with name validation.

Challenge

A Cookie header is a single line: name1=value1; name2=value2; name3=value3.

Implement int find_cookie(const char *header, const char *name, char *out_value, int cap).

  • Skip leading whitespace after each ;.
  • Match name exactly (case-sensitive).
  • Copy the value to out_value, NUL-terminated.
  • Return 1 if found, 0 if not.

Reject (return 0) if the requested name contains any of: =, ;, \r, \n, space.

Why this matters

Every web server, every WAF, every analytics tag needs to read Cookie headers. Doing it strictly catches malformed cookies that smuggle attacks.

Input format

Header string + cookie name + output buffer.

Output format

0/1 + value.

Constraints

Strict — no permissive whitespace inside name.

Starter code

int find_cookie(const char *header, const char *name, char *out_value, int cap) { /* TODO */ (void)header; (void)name; (void)out_value; (void)cap; return 0; }

Common mistakes

Using strstr — matches bar=x inside foobar=x. Use word-boundary matching.

Edge cases to handle

Empty header. Cookie with empty value (name=;). Multiple instances (use first).

Complexity

O(strlen).

Background lessons

Up next

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