Python Port Scanner (Educational)

Goal: understand TCP connect behavior + timeouts using Python sockets (authorized environments only).

Overview

This writeup documents a small script that attempts TCP connections to a list of ports and reports which ones accept connections.

Python Networking

What I learned

• connect_ex returns 0 on success
• timeouts matter for speed & accuracy
• basic error handling and clean loops

port_scan.py
import socket

def scan(host: str, ports: range, timeout: float = 0.4) -> list[int]:
    open_ports = []
    for port in ports:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(timeout)
            if s.connect_ex((host, port)) == 0:
                open_ports.append(port)
    return open_ports

if __name__ == "__main__":
    # Use only on systems you own or have explicit permission to test.
    target = "127.0.0.1"
    ports = range(1, 1025)

    result = scan(target, ports)
    print("Target:", target)
    print("Open ports:", result if result else "None")

Ethics note

This is for learning. Don’t scan networks or systems you don’t own / don’t have explicit authorization to test.