networking · advanced · ~15 min
Iterate, attempt connect, classify.
Probe a range of TCP ports on your own loopback interface and report which ones accept connections.
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.
lo, hi: the inclusive port range to scan.out_count: pointer that receives how many open ports were found.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.
two listeners open on ports p1, p2 within [lo, hi]
-> scan_local(lo, hi, &n) includes p1 and p2; n >= 2
*out_count = 0.NULL if an allocation fails.127.0.0.1. Scanning third-party hosts without consent is unauthorised and out of scope here. The caller frees the result.Inclusive port range lo..hi and an out_count pointer for the result size.
A malloc'd array of open loopback ports (caller frees); *out_count set to its length.
Connect only to 127.0.0.1; the caller frees the result.
#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.