networking · advanced · ~15 min

Find open ports on localhost

Iterate, attempt connect, classify.

Challenge

Probe a range of TCP ports on your own loopback interface and report which ones accept connections.

Task

Implement int *scan_local(int lo, int hi, size_t *out_count) that returns a freshly malloc-ed array of the open TCP ports on 127.0.0.1 in the inclusive range [lo, hi], and sets *out_count to the number found. No main — the grader calls it.

Input

  • lo, hi: the inclusive port range to scan.
  • out_count: pointer that receives how many open ports were found.

Output

A malloc-ed array of the open port numbers (length *out_count). The caller frees it. *out_count is 0 (and you may return NULL or an empty allocation) if none are open.

Example

two listeners open on ports p1, p2 within [lo, hi]
  ->   scan_local(lo, hi, &n) includes p1 and p2; n >= 2

Edge cases

  • No open ports in range: set *out_count = 0.
  • Return NULL if an allocation fails.

Rules

  • Connect only to 127.0.0.1. Scanning third-party hosts without consent is unauthorised and out of scope here. The caller frees the result.

Input format

Inclusive port range lo..hi and an out_count pointer for the result size.

Output format

A malloc'd array of open loopback ports (caller frees); *out_count set to its length.

Constraints

Connect only to 127.0.0.1; the caller frees the result.

Starter code

#include <stdlib.h>
#include <stddef.h>

int *scan_local(int lo, int hi, size_t *out_count) {
    /* TODO */
    *out_count = 0;
    return NULL;
}

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