networking · beginner · ~20 min
Use snprintf for safe formatted construction.
Assemble the bytes of an HTTP/1.1 GET request as a string — the C equivalent of what curl -X GET sends.
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).
host, path: NUL-terminated strings.out: caller-provided buffer.cap: capacity of out in bytes.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.
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"
cap that exactly fits the request plus NUL succeeds.cap one byte short returns -1.out.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.
host and path are NUL-terminated strings; out is a buffer of cap bytes.
Bytes written excluding the NUL, or -1 if the request would not fit in cap.
Always NUL-terminate and never overflow out. The final blank line terminates the headers.
#include <stddef.h>
int build_http_get(const char *host, const char *path, char *out, size_t cap) { /* TODO */ return -1; }
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.
cap exactly fits — should succeed. cap one short — should return -1.
O(host + path).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.