networking · advanced · ~15 min

Find open ports on localhost

Iterate, attempt connect, classify.

Challenge

Implement int *scan_local(int lo, int hi, size_t *out_count) that returns a freshly malloc'd array of open TCP ports on 127.0.0.1 in the inclusive range [lo, hi]. Set *out_count to the size; the caller frees.

Strictly local. Do not attempt to connect to anything other than 127.0.0.1. Hosts other than loopback are not allowed here — production "scanning" of third-party hosts without permission is unethical and illegal in many jurisdictions.

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.