networking · beginner · ~15 min
Format a connection endpoint string.
Format a connection endpoint as the familiar host:port string.
Implement int build_endpoint(char *out, int outsz, const char *host, int port) that writes "host:port" into out (bounded by outsz) and returns the length of the resulting string. Using snprintf does both at once.
out, outsz: destination buffer and its size.host: the host name.port: the port number.Returns the length of the host:port string (the value snprintf returns).
build_endpoint(out, 64, "example.com", 443) -> 15, out="example.com:443"
snprintf truncates safely if the buffer is too small but still returns the would-be length.An output buffer (out) with size (outsz), a host string, and a port number.
The length of the formatted host:port string.
Use snprintf with outsz so the write stays bounded.
#include <stdio.h>
int build_endpoint(char *out, int outsz, const char *host, int port) {
/* TODO */
return 0;
}
Assuming read/write transmits all requested bytes at once; ignoring socket file descriptor cleanup; unhandled endianness conversions.
Short reads/writes; peer closing socket (recv returns 0); signal interruption (EINTR); non-blocking EAGAIN.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.