networking · intermediate · ~15 min
Split an endpoint into host and numeric port.
Split an endpoint string of the form host:port back into its host and numeric port.
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.
s: the host:port string.host, hostsz: destination buffer for the host part and its size.port: out-pointer for the parsed port.Returns 1 on success (host and port written), or 0 if there is no : or the port is out of range.
parse_endpoint("host:8080", h, 64, &p) -> 1, h="host", p=8080
parse_endpoint("hostonly", h, 64, &p) -> 0 (no colon)
: in the string: return 0.1..65535: return 0.hostsz and NUL-terminate it.The host:port string (s), a host buffer (host) with size (hostsz), and a port out-pointer.
Returns 1 with host and *port written, or 0 if there is no ':' or the port is invalid.
Split on ':'. Copy the host bounded by hostsz and NUL-terminate. Reject a port outside 1..65535.
#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.