networking · advanced · ~15 min

Parse a port number

Validate and parse a TCP port string (1–65535).

Challenge

Before binding a one-shot server you validate the port it was asked to use. Implement the parser:

int parse_port(const char *s, uint16_t *out);

Valid ports are 1–65535 with no leading zeros, sign, or trailing characters. Return 1 and set *out on success, 0 otherwise.

Input format

A NUL-terminated string.

Output format

1 + *out on success; 0 otherwise.

Constraints

Port 0 is reserved (invalid here). Reject leading zeros, signs, and any non-digit.

Starter code

#include <stdint.h>
/* Parse a TCP port string into *out. Valid ports are 1..65535 with no leading
   zeros, sign, or trailing characters. Return 1 on success, 0 otherwise. */
int parse_port(const char *s, uint16_t *out){ (void)s;(void)out; return 0; }

Common mistakes

Accepting port 0; integer-overflowing past 65535; allowing trailing characters.

Edge cases to handle

"1" and "65535" are the bounds; "0", "65536", "080", "12x" are invalid.

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