01 / BUILD A TCP PORT SCANNER · LESSON 01

Start with an explicit scan plan

Build a bounded, canonical endpoint plan before any TCP probe can run.

15 min · learn at your pace

Separate deciding from connecting

A scanner has two different jobs: decide which endpoints belong in the assessment, then observe them. Keep planning as a pure function. It should return ordinary records without opening sockets or changing files. The plan can be reviewed, tested and reused with either a browser teaching adapter or a local TCP implementation.

Use numeric IP addresses in this course. A hostname introduces resolution, multiple returned addresses and a separate timeout policy. A literal IPv4 or IPv6 address makes the requested endpoint unambiguous. Canonicalize equivalent IPv6 spellings before deduplicating them; compare parsed addresses numerically rather than sorting their text.

Validate the complete request

The allowlist describes permitted ranges, while the target list identifies the addresses to assess. Never expand an entire allowlist into targets. Reject an out-of-scope target even when other targets are valid. A partially accepted request can hide a mistake in the caller's intended scope.

Ports are integers from 1 through 65535. Python's bool is an int subclass, so use an explicit type check when True must not become port 1. Deduplicate targets and ports before enforcing the endpoint ceiling, and accept the ceiling itself. Empty valid inputs produce an empty plan.

The browser lab sends no packets. Later lessons inject recorded observations into this plan, and the optional downloadable scanner uses the same planning rules on a local machine. An allowlist is a program boundary; it does not establish permission to assess someone else's system.

Try an example.py
from ipaddress import ip_address
print(str(ip_address("2001:0db8::10")))
print(sorted({443, 80, 443}))
YOUR TURN

Put it into practice.

Define scan_plan(targets, ports, allowed, max_endpoints=64). All three collections must be lists. Targets are unscoped numeric IP strings; reject unspecified, multicast and IPv6 link-local addresses. Every target must be in at least one strict CIDR string in allowed. Validate every item before returning a plan. Ports are integers 1..65535 excluding bool. Normalize/deduplicate targets and ports; order IPv4 before IPv6, numerically by address, then port. Return address/port dictionaries. max_endpoints must be an integer 1..256 excluding bool; reject a larger deduplicated plan. Empty valid lists may yield []. Invalid input raises ValueError. Never probe or enumerate an allowed subnet.

See an explained solution
One way to solve it.py
from ipaddress import ip_address, ip_network

def scan_plan(targets, ports, allowed, max_endpoints=64):
    if type(max_endpoints) is not int or not 1 <= max_endpoints <= 256:
        raise ValueError("max_endpoints must be 1..256")
    if any(not isinstance(value, list) for value in (targets, ports, allowed)):
        raise ValueError("Use lists for targets, ports and allowed prefixes")
    networks = []
    for value in allowed:
        if not isinstance(value, str) or "/" not in value or "%" in value:
            raise ValueError("Use unscoped CIDR allowlists")
        networks.append(ip_network(value.strip(), strict=True))
    addresses = set()
    for value in targets:
        if not isinstance(value, str) or "%" in value:
            raise ValueError("Use numeric unscoped IP targets")
        address = ip_address(value.strip())
        if address.is_unspecified or address.is_multicast or (address.version == 6 and address.is_link_local):
            raise ValueError("Target cannot be used by this scanner")
        if not any(address.version == network.version and address in network for network in networks):
            raise ValueError("Target is outside the allowed scope")
        addresses.add(address)
    if any(type(port) is not int or not 1 <= port <= 65535 for port in ports):
        raise ValueError("Ports must be integers 1..65535")
    unique_ports = sorted(set(ports))
    if len(addresses) * len(unique_ports) > max_endpoints:
        raise ValueError("Endpoint limit exceeded")
    return [{"address":str(address), "port":port}
            for address in sorted(addresses, key=lambda value:(value.version, int(value)))
            for port in unique_ports]

if __name__ == "__main__":
    print(scan_plan(["192.0.2.10"], [443, 80], ["192.0.2.0/24"]))

Planning has no side effects. Canonical addresses avoid duplicate work, while exact scope and count checks apply equally to recorded and real probes.