01 / BUILD A TCP PORT SCANNER · LESSON 02

Give TCP observations a precise shape

Use immutable records to distinguish open, refused, timed-out and failed probes.

15 min · learn at your pace

A result is more than a boolean

An open TCP connection means a handshake succeeded. It does not prove that the expected application is listening, that authentication works, or that the service is healthy. A refusal is different from a timeout. A timeout may reflect filtering, packet loss or a slow path; it is not proof that a port is closed. Preserve these distinctions in the data model.

A frozen dataclass gives each observation named fields and prevents ordinary reassignment after construction. Type annotations document intent but do not validate runtime values. Put boundary validation in post_init so an impossible port, negative duration or unknown state cannot silently enter a report.

Normalize once at the boundary

The constructor accepts equivalent textual IP forms and stores canonical text. A frozen record can normalize its own fields during construction using object.setattr; callers should not use that escape hatch to mutate an observation later. asdict creates a serializable mapping for the report boundary.

StrEnum makes state values readable while retaining string-compatible values. Keep diagnostic detail as text and keep elapsed milliseconds numeric. Reject non-finite durations such as NaN, as comparisons and JSON reports become misleading when those values leak through. Also reject boolean durations and ports rather than accepting Python's numeric subclass behavior accidentally.

This is a teaching record for an individual observation. It contains no credentials or application payloads. The next lesson composes these records into a scanner whose probe can be replaced without changing the scan policy.

Try an example.py
from dataclasses import dataclass, asdict
@dataclass(frozen=True)
class Endpoint:
    address: str
    port: int
print(asdict(Endpoint("192.0.2.10", 443)))
YOUR TURN

Put it into practice.

Create ProbeState(StrEnum) with OPEN="open", REFUSED="refused", TIMED_OUT="timed_out", ERROR="error". Create frozen dataclass ProbeResult(address, port, state, elapsed_ms, detail=""). Normalize a string unscoped IP address. Require integer port 1..65535 excluding bool, one of those four state strings, finite nonnegative numeric elapsed_ms excluding bool, and a string detail. Invalid values raise ValueError. Fields must be available to dataclasses.asdict; ordinary assignment must fail.

See an explained solution
One way to solve it.py
from dataclasses import dataclass, asdict
from enum import StrEnum
from ipaddress import ip_address
import math

class ProbeState(StrEnum):
    OPEN = "open"
    REFUSED = "refused"
    TIMED_OUT = "timed_out"
    ERROR = "error"

@dataclass(frozen=True)
class ProbeResult:
    address: str
    port: int
    state: str
    elapsed_ms: float
    detail: str = ""

    def __post_init__(self):
        if not isinstance(self.address, str) or "%" in self.address:
            raise ValueError("Invalid address")
        object.__setattr__(self, "address", str(ip_address(self.address.strip())))
        if type(self.port) is not int or not 1 <= self.port <= 65535:
            raise ValueError("Invalid port")
        if not isinstance(self.state, str) or self.state not in {value.value for value in ProbeState}:
            raise ValueError("Invalid probe state")
        if type(self.elapsed_ms) not in (int, float) or not math.isfinite(self.elapsed_ms) or self.elapsed_ms < 0:
            raise ValueError("Invalid elapsed time")
        if not isinstance(self.detail, str):
            raise ValueError("Detail must be text")

if __name__ == "__main__":
    print(asdict(ProbeResult("192.0.2.10", 443, "open", 3.5)))

The immutable record preserves distinct outcomes and validates values when they cross into the program. Tests inspect the public shape and behavior rather than a particular constructor layout.