networking · intermediate · ~15 min
Emit a status line, Content-Length, and body.
Assemble the bytes of a minimal HTTP/1.1 response: a status line, a Content-Length header, a blank line, and the body.
Implement int build_response(char *out, int outsz, int code, const char *body) that writes this exact response into out and returns its length:
HTTP/1.1 <code> OK\r\nContent-Length: <len>\r\n\r\n<body>
where <len> is strlen(body).
out, outsz: destination buffer and its size.code: the numeric status code (e.g. 200).body: the response body string.Returns the length of the response written (the snprintf return value).
build_response(out, 256, 200, "hi") -> out="HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi"
OK after the code, and CRLF (\r\n) line endings.An output buffer (out) with size (outsz), a status code, and a body string.
The length of the written response.
Format: 'HTTP/1.1 OK\r\nContent-Length:
#include <stdio.h>
#include <string.h>
int build_response(char *out, int outsz, int code, const char *body) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.