networking · beginner · ~20 min

Build an HTTP GET request

Use snprintf for safe formatted construction.

Challenge

Assemble the bytes of an HTTP/1.1 GET request as a string — the C equivalent of what curl -X GET sends.

Task

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 into out (NUL-terminated).

Input

  • host, path: NUL-terminated strings.
  • out: caller-provided buffer.
  • cap: capacity of out in bytes.

Output

Write exactly these four lines (CRLF line endings):

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

Return the number of bytes written (excluding the trailing NUL), or -1 if the full request plus NUL would not fit in cap.

Example

build_http_get("example.com", "/", buf, 256)
  -> 56, buf = "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n"
build_http_get("example.com", "/", tiny, 10)   -> -1   (won't fit)
build_http_get("api.example.org", "/v1/things?x=1", buf, 300)
  -> >0, buf contains "Host: api.example.org\r\n"

Edge cases

  • A cap that exactly fits the request plus NUL succeeds.
  • A cap one byte short returns -1.

Rules

  • Always NUL-terminate; never overflow out.

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 NUL-terminated strings; out is a buffer of cap bytes.

Output format

Bytes written excluding the NUL, or -1 if the request would not fit in cap.

Constraints

Always NUL-terminate and never overflow out. The final blank line terminates the headers.

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.