networking · intermediate · ~15 min

Parse a host:port string

Split an endpoint into host and numeric port.

Challenge

Split an endpoint string of the form host:port back into its host and numeric port.

Task

Implement int parse_endpoint(const char *s, char *host, int hostsz, int *port) that splits s at the :, copying the host part into host (bounded by hostsz) and writing the numeric port into *port.

Input

  • s: the host:port string.
  • host, hostsz: destination buffer for the host part and its size.
  • port: out-pointer for the parsed port.

Output

Returns 1 on success (host and port written), or 0 if there is no : or the port is out of range.

Example

parse_endpoint("host:8080", h, 64, &p)   ->   1, h="host", p=8080
parse_endpoint("hostonly",  h, 64, &p)   ->   0   (no colon)

Edge cases

  • No : in the string: return 0.
  • A port outside 1..65535: return 0.
  • Copy the host bounded by hostsz and NUL-terminate it.

Input format

The host:port string (s), a host buffer (host) with size (hostsz), and a port out-pointer.

Output format

Returns 1 with host and *port written, or 0 if there is no ':' or the port is invalid.

Constraints

Split on ':'. Copy the host bounded by hostsz and NUL-terminate. Reject a port outside 1..65535.

Starter code

#include <string.h>
#include <stdlib.h>

int parse_endpoint(const char *s, char *host, int hostsz, int *port) {
    /* TODO */
    return 0;
}

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