cybersecurity · intermediate · ~18 min · safe pentest lab

Detect port scanners in a connection log

Per-key fan-out counting over a text log.

Challenge

Your job

int count_scanners(const char *log, int threshold);

log is newline-separated "<src_ip> <dst_port>" lines. Return how many source IPs connected to more than threshold distinct destination ports. NULL → 0.

Bounded for this exercise: at most 64 distinct IPs, 128 distinct ports each.

Hints

  1. Parse each line with sscanf(line, "%39s %d", ip, &port).
  2. Keep a small table of IPs → set of distinct ports.
  3. Count IPs whose distinct-port count exceeds threshold.

Why this matters

A host that touches many distinct ports in a short window is the classic port-scan signature. Counting fan-out per source IP is the detection.

Starter code

int count_scanners(const char *log, int threshold) {
    /* TODO */
    (void)log; (void)threshold;
    return 0;
}

Common mistakes

Counting repeated (ip,port) pairs more than once. Off-by-one on the threshold (it's exclusive).

Edge cases to handle

Empty log. Duplicate lines. An IP exactly at the threshold (not counted).

Complexity

O(lines × distinct-ports).

Background lessons

Up next

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