networking · beginner · ~15 min
Strict integer parsing with a domain check.
Turn a port-number string from an untrusted argument into a validated integer.
Implement int parse_port(const char *s) that parses a TCP/UDP port number.
s: a string that should contain only decimal digits (may be NULL or empty).Return the port number if it is a valid 1..65535, otherwise return -1 (non-digit characters, empty/NULL, 0, or out of range).
"8080" -> 8080
"1" -> 1
"65535" -> 65535
"70000" -> -1 (out of range)
"0" -> -1 (port 0 not allowed)
"-1" -> -1 ('-' is not a digit)
"8080a" -> -1 (trailing non-digit)
"" -> -1
0 is rejected; valid range is 1..65535.-) makes the whole string invalid.s: a string expected to hold only decimal digits (may be NULL/empty).
The port as an int if in 1..65535, else -1.
Reject non-digit characters, empty/NULL, 0, and anything outside 1..65535.
int parse_port(const char *s) { /* TODO */ return -1; }
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.