networking · beginner · ~15 min

Build a host:port string

Format a connection endpoint string.

Challenge

Format a connection endpoint as the familiar host:port string.

Task

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.

Input

  • out, outsz: destination buffer and its size.
  • host: the host name.
  • port: the port number.

Output

Returns the length of the host:port string (the value snprintf returns).

Example

build_endpoint(out, 64, "example.com", 443)   ->   15, out="example.com:443"

Edge cases

  • snprintf truncates safely if the buffer is too small but still returns the would-be length.

Input format

An output buffer (out) with size (outsz), a host string, and a port number.

Output format

The length of the formatted host:port string.

Constraints

Use snprintf with outsz so the write stays bounded.

Starter code

#include <stdio.h>

int build_endpoint(char *out, int outsz, const char *host, int port) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.