cybersecurity · beginner · ~15 min · safe pentest lab

Classify a TCP/UDP Port Number

Practice deny-by-default input validation: reject attacker-controlled out-of-range integers before classifying, mapping a value to fixed IANA port ranges with correct, non-overlapping boundaries.

Challenge

During a defensive port-scan review, your tooling parses port numbers pulled from an attacker-influenced source (a scan target list, a config field, or a captured packet). A naive parser trusts that value and indexes tables or opens sockets with it — but a hostile input can be negative or far above the valid 16-bit range, corrupting later logic. Your job is a pure, deny-by-default classifier that never touches the network: given an integer port, decide which IANA range it belongs to.

Return 0 for well-known ports (0..1023), 1 for registered ports (1024..49151), 2 for dynamic/ephemeral ports (49152..65535), and -1 for anything out of the valid range (< 0 or > 65535). Bounds-check the value BEFORE using it for anything else — reject invalid input first, then classify.

Example

port_class(80) -> 0 port_class(8080) -> 1 port_class(49152) -> 2 port_class(-1) -> -1

Input format

A single int port, which may hold any value representable by int (including negatives and values above 65535).

Output format

An int: 0 (well-known), 1 (registered), 2 (dynamic/ephemeral), or -1 (out of range).

Constraints

Pure function: no I/O, no sockets, no allocation. Valid port range is 0..65535 inclusive. Reject out-of-range input by returning -1. Do not assume the input is already validated.

Starter code

int port_class(int port){
    /* TODO: reject out-of-range ports, then classify by IANA range.
       Replace this stub — it fails the tests on purpose. */
    return -1;
}

Common mistakes

Forgetting the negative-input check and returning 0 for a negative port; off-by-one at the 1023/1024 or 49151/49152 boundaries; using >= / <= inconsistently so a boundary port is misclassified or double-counted; classifying first and validating later so an out-of-range value slips through.

Edge cases to handle

port = -1 and other negatives -> -1; port = 0 -> 0; port = 1023/1024 boundary between well-known and registered; port = 49151/49152 boundary between registered and dynamic; port = 65535 -> 2; port = 65536 and larger -> -1.

Background lessons

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