networking · beginner · ~15 min

Valid port number?

Bound-check a port number.

Challenge

Check whether an integer is a usable TCP/UDP port number.

Task

Implement int is_valid_port(int p) that returns 1 if p is in the usable port range 1..65535, otherwise 0.

Input

One int p (may be 0, negative, or larger than 65535).

Output

Returns 1 for a valid port, 0 otherwise.

Example

is_valid_port(80)      ->   1
is_valid_port(65535)   ->   1
is_valid_port(0)       ->   0
is_valid_port(70000)   ->   0

Edge cases

  • Port 0 is reserved ("pick any") and is not valid here.
  • 65535 is the maximum 16-bit value and is valid.

Input format

One integer p.

Output format

1 if 1 <= p <= 65535, else 0.

Constraints

Valid range is 1..65535 inclusive; 0 is not valid.

Starter code

int is_valid_port(int p) {
    /* TODO */
    return 0;
}

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