networking · advanced · ~15 min

Count ports in a range

Parse a port range like "80-90" and count the ports it covers.

Challenge

A scan is driven by a port range. Parse one and report its size:

int count_ports_in_range(const char *s);

Accept "lo-hi" (inclusive) or a single "port". Return how many ports it covers, or −1 if malformed or out of the 1–65535 range.

Input format

A NUL-terminated string.

Output format

Port count, or −1.

Constraints

Both endpoints must be 1–65535 with lo <= hi. A single port covers 1.

Starter code

#include <stddef.h>
/* Parse a port range like "80-90" (inclusive) or a single port "443" and return
   how many ports it covers. Ports must be 1..65535 with lo<=hi and no junk;
   return -1 if the range is malformed or out of bounds. */
int count_ports_in_range(const char *s){ (void)s; return -1; }

Common mistakes

Off-by-one in hi-lo+1; accepting a reversed range; not validating the upper bound.

Edge cases to handle

"80-90"→11, "443"→1, "1-65535"→65535; "90-80", "0-10", "80-" are invalid.

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