01 / BUILD A TCP PORT SCANNER · LESSON 03

Build a scanner with a replaceable probe

Compose validated scan policy with an injected TCP observation function.

20 min · learn at your pace

Keep policy separate from transport

The scanner owns scope validation, stable ordering and complete result rows. A probe owns the attempt to observe one endpoint. Passing the probe as an argument keeps both responsibilities testable. The browser uses RecordedProbe from lab_probe.py, which reads fictional observations from tcp.json. It never creates sockets, resolves names or sleeps.

Use the supplied scan_rules helpers to build the entire plan before calling the probe. Each call receives the canonical address, integer port and timeout in milliseconds. Convert a returned observation into a validated ProbeResult. Missing fields or impossible values should produce an error row for that endpoint, allowing later endpoints to remain visible.

Catch failures without catching cancellation

Handle TimeoutError and ConnectionRefusedError distinctly. Then catch ordinary Exception for unexpected adapter errors or malformed returned data. Do not catch BaseException: KeyboardInterrupt and SystemExit are not failed TCP observations. A caller that cancels work must be able to stop the scan.

An exception does not provide a trustworthy measured duration. This contract uses the requested deadline for a timeout and zero for other exception-only rows. Recorded successful durations remain supplied observations, not measurements of browser execution speed.

Move the same idea to your own lab

The optional local download replaces the recorded probe with Python sockets. It prints a plan by default and connects only with --execute. Required course checks still run entirely in this browser. Keep the four observation states when adapting the tool: an open handshake, a refusal, a deadline and an execution error describe different evidence.

Download the local Python TCP scanner
Try an example.py
from lab_probe import RecordedProbe
probe = RecordedProbe()
print(probe("192.0.2.10", 443, 500))
YOUR TURN

Put it into practice.

Define scan(targets, ports, allowed, probe, timeout_ms=500, max_endpoints=64). Use the supplied scan_rules plan/record contract. Validate timeout_ms as integer 1..5000 excluding bool before any probe. Validate the entire plan first. Call probe(address, port, timeout_ms) exactly once per endpoint in plan order. Return address, port, state, elapsed_ms, detail dictionaries. Validate returned state/duration/detail. TimeoutError becomes timed_out with elapsed_ms=timeout_ms and detail="TimeoutError"; ConnectionRefusedError becomes refused/0/"ConnectionRefusedError". Other Exceptions, including invalid returned values, become error/0 with their exception class name as detail. Continue after ordinary failures; propagate KeyboardInterrupt and SystemExit. No sockets are needed in the browser.

See an explained solution
One way to solve it.py
from dataclasses import asdict
from scan_rules import scan_plan, ProbeResult

def scan(targets, ports, allowed, probe, timeout_ms=500, max_endpoints=64):
    if type(timeout_ms) is not int or not 1 <= timeout_ms <= 5000:
        raise ValueError("timeout_ms must be 1..5000")
    plan=scan_plan(targets, ports, allowed, max_endpoints)
    results=[]
    for endpoint in plan:
        try:
            raw=probe(endpoint["address"], endpoint["port"], timeout_ms)
            result=ProbeResult(**endpoint, state=raw["state"], elapsed_ms=raw["elapsed_ms"], detail=raw.get("detail",""))
        except TimeoutError:
            result=ProbeResult(**endpoint, state="timed_out", elapsed_ms=timeout_ms, detail="TimeoutError")
        except ConnectionRefusedError:
            result=ProbeResult(**endpoint, state="refused", elapsed_ms=0, detail="ConnectionRefusedError")
        except Exception as error:
            result=ProbeResult(**endpoint, state="error", elapsed_ms=0, detail=type(error).__name__)
        results.append(asdict(result))
    return results

if __name__ == "__main__":
    from lab_probe import RecordedProbe
    print(scan(["192.0.2.10"], [22,443], ["192.0.2.0/24"], RecordedProbe()))

The injected probe makes behavior testable without networking. Every ordinary failure remains an observation, while cancellation stops the operation instead of being converted into misleading rows.