01 / BUILD A TCP PORT SCANNER · LESSON 04

Compare observations with expected services

Keep unknown exposure distinct from a confirmed TCP refusal or an unexpected listener.

15 min · learn at your pace

Join intent with evidence

A list of open ports is difficult to act on without expected service information. Join observations with a small service policy by address and port. The service name is a label from that policy, not a banner discovered from the remote application. Never infer a protocol solely from its conventional port number.

Use the union of observation and expectation keys. An expected endpoint that was never scanned must remain in the report as not_scanned. Otherwise a partial assessment can appear complete merely because no result row exists. Reject duplicate keys so an arbitrary later record cannot replace earlier evidence silently.

Preserve uncertainty

An open expected port is expected_open; a refused expected port is expected_refused. An open port with no expectation is unexpected_open. A refused unlisted endpoint is no_listener for this observation. Timeouts, probe errors and missing scans all produce unknown, regardless of the expected service label.

These labels are assessment rules, not vulnerability verdicts. An unexpected listener needs investigation; it does not prove malicious activity. A refusal records one moment and path, and an expected open port still requires application-level monitoring outside this course.

The input records in this lesson are already normalized and validated by the earlier scanner. Keep that precondition explicit instead of silently applying a second, different parsing policy. Return ordinary dictionaries in numeric address order so later CSV and JSON exports stay reproducible.

Try an example.py
observed = {("192.0.2.10", 443): "open"}
expected = {("192.0.2.10", 443): "portal", ("192.0.2.10", 22): "admin"}
print(sorted(observed.keys() | expected.keys()))
YOUR TURN

Put it into practice.

Define exposure_report(results, expected). Inputs have canonical IPs, valid ports and scanner states; expected rows have a service string. Reject duplicate address/port keys within either input with ValueError. Include the union of keys and order by IP version, numeric address and port. Return address, port, service (empty if unlisted), state (not_scanned if missing), finding. timed_out/error/not_scanned => unknown; expected open/refused => expected_open/expected_refused; unlisted open/refused => unexpected_open/no_listener. Do not modify inputs.

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

def exposure_report(results, expected):
    observed={};wanted={}
    for row in results:
        key=(row["address"],row["port"])
        if key in observed:raise ValueError("Duplicate observation")
        observed[key]=row["state"]
    for row in expected:
        key=(row["address"],row["port"])
        if key in wanted:raise ValueError("Duplicate expectation")
        wanted[key]=row["service"]
    report=[]
    for address,port in sorted(set(observed)|set(wanted),key=lambda key:(ip_address(key[0]).version,int(ip_address(key[0])),key[1])):
        key=(address,port);state=observed.get(key,"not_scanned");service=wanted.get(key,"")
        if state in ("timed_out","error","not_scanned"):finding="unknown"
        elif key in wanted:finding="expected_open" if state=="open" else "expected_refused"
        else:finding="unexpected_open" if state=="open" else "no_listener"
        report.append({"address":address,"port":port,"service":service,"state":state,"finding":finding})
    return report

if __name__ == "__main__":
    print(exposure_report([{"address":"192.0.2.10","port":443,"state":"open"}], [{"address":"192.0.2.10","port":443,"service":"portal"}]))

The report compares intended services with actual observations without turning silence into evidence. Stable identities and ordering make later reports trustworthy.