networking · beginner · ~15 min

Parse a port number string

Strict integer parsing with a domain check.

Challenge

Turn a port-number string from an untrusted argument into a validated integer.

Task

Implement int parse_port(const char *s) that parses a TCP/UDP port number.

Input

  • s: a string that should contain only decimal digits (may be NULL or empty).

Output

Return the port number if it is a valid 1..65535, otherwise return -1 (non-digit characters, empty/NULL, 0, or out of range).

Example

"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

Edge cases

  • Port 0 is rejected; valid range is 1..65535.
  • Any non-digit character (including a leading -) makes the whole string invalid.

Input format

s: a string expected to hold only decimal digits (may be NULL/empty).

Output format

The port as an int if in 1..65535, else -1.

Constraints

Reject non-digit characters, empty/NULL, 0, and anything outside 1..65535.

Starter code

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.