networking · beginner · ~20 min
Use snprintf for safe formatted construction.
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.
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 null-terminated. out has cap bytes.
Bytes written or -1.
Use snprintf. Always NUL-terminate.
#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.