networking · beginner · ~20 min

Build an HTTP GET request

Use snprintf for safe formatted construction.

Challenge

Implement int build_http_get(const char *host, const char *path, char *out, size_t cap) that writes a minimal HTTP/1.1 GET request to out:

GET <path> HTTP/1.1\r\n
Host: <host>\r\n
Connection: close\r\n
\r\n

Returns the number of bytes written (excluding the trailing NUL), or -1 if it wouldn't fit.

Why this matters

Before you can speak HTTP over a socket, you need to assemble the byte stream. This is the C equivalent of curl -X GET — assembling the wire format directly.

Input format

host and path are null-terminated. out has cap bytes.

Output format

Bytes written or -1.

Constraints

Use snprintf. Always NUL-terminate.

Starter code

#include <stddef.h>
int build_http_get(const char *host, const char *path, char *out, size_t cap) { /* TODO */ return -1; }

Common mistakes

Trusting snprintf's return value to mean 'bytes written' when the buffer overflowed (snprintf returns the would-be length); forgetting the empty line that terminates the headers.

Edge cases to handle

cap exactly fits — should succeed. cap one short — should return -1.

Complexity

O(host + path).

Background lessons

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