Port scanner for my own network
The goal
I wanted to see for myself what a port scanner actually does, by checking which doors are open on a machine I own.
What you need
Python 3, and about an hour. No extra libraries, socket is built into Python.
How I built it
The scanner tries to open a TCP connection to a list of common ports, one at a time. If the connection succeeds, the port is open; if it fails or times out, it’s closed or blocked. I kept the port list short (12 common ones like SSH, HTTP, HTTPS, MySQL) rather than scanning all 65,535, since that would be slow and isn’t necessary for learning the idea.
Python
import socket
from datetime import datetime
COMMON_PORTS = {
21: “FTP”, 22: “SSH”, 23: “Telnet”, 25: “SMTP”, 53: “DNS”,
80: “HTTP”, 110: “POP3”, 143: “IMAP”, 443: “HTTPS”,
3306: “MySQL”, 3389: “RDP”, 8080: “HTTP (alt)”,
}
def scan_port(target, port, timeout=0.5):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
try:
return sock.connect_ex((target, port)) == 0
finally:
sock.close()
def scan_target(target, ports=COMMON_PORTS):
return [(p, s) for p, s in ports.items() if scan_port(target, p)]
if name == “main“:
target = input(“Enter a target to scan (e.g. 127.0.0.1): “).strip() or “127.0.0.1”
start = datetime.now()
open_ports = scan_target(target)
duration = (datetime.now() – start).total_seconds()
for port, service in open_ports:
print(f”{port}/tcp open {service}”)
print(f”Scan finished in {duration:.2f} seconds.”)
Run it with:
python3 port_scanner.py
What broke
My first version had no timeout on the connection attempt, so scanning a port that silently drops traffic (instead of refusing it) made the whole script hang for a long time. Adding sock.settimeout(0.5) fixed it, the scan now moves on after half a second if nothing answers.
What I learned
An “open” port isn’t automatically dangerous, lots of normal software needs open ports to work. What matters is whether something open is supposed to be open, and whether it’s protected properly. Scanning your own machine is a good way to actually see what’s running and exposed, instead of assuming.
Try it yourself
Scan a wider range of ports instead of just the common list, or add a simple banner grab that reads the first bit of data a port sends back, which often reveals what software is running on it.
The full code is on GitHub.
