networking · intermediate · ~15 min

Build an HTTP GET request

Construct a valid HTTP request line + Host header.

Challenge

Assemble the bytes of a minimal HTTP/1.1 GET request as a string.

Task

Implement int build_get(char *out, int outsz, const char *host, const char *path) that writes this exact request into out:

GET <path> HTTP/1.1\r\nHost: <host>\r\n\r\n

Input

  • out, outsz: destination buffer and its size.
  • host, path: NUL-terminated strings.

Output

Return the length of the request string written.

Example

build_get(b, 256, "example.com", "/index.html")
  -> b = "GET /index.html HTTP/1.1\r\nHost: example.com\r\n\r\n"

Rules

  • End the request with a blank line (\r\n\r\n) to terminate the headers.

Input format

out/outsz: destination buffer and size; host and path: NUL-terminated strings.

Output format

The length of the request string written into out.

Constraints

Use the exact CRLF layout and end with a blank line.

Starter code

#include <stdio.h>

int build_get(char *out, int outsz, const char *host, const char *path) {
    /* TODO */
    return 0;
}

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