A port scanner is the 'hello world' of ethical hacking tools — and the fastest way to understand how computers expose services to a network. You'll build a working one in about 15 lines using Python's built-in socket module. Run it only against your own machine or lab.
What a port actually is
A single server runs many services at once — a website, email, SSH. Ports are the numbered doors that keep them apart: web on 80, HTTPS on 443, SSH on 22. Scanning asks each door, politely, 'is anyone home?'
The core idea: try to connect
Checking a port is just attempting a TCP connection. If it succeeds, the port is open.
import socket
def scan(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
result = s.connect_ex((host, port)) # 0 means success
s.close()
return result == 0
connect_ex returns 0 when the port is open and an error code otherwise — so it never crashes, it just reports.
Scanning a range of ports
target = '127.0.0.1'
for port in range(20, 1025):
if scan(target, port):
print(f'[+] Port {port} is open')
Run it against your own machine and you'll see exactly which services you're exposing.
| Piece | Job |
|---|---|
socket.socket(...) | Creates a TCP connection object |
settimeout(1) | Don't wait forever on a dead port |
connect_ex | Try to connect; return 0 if open |
range(20, 1025) | The well-known port range to check |
Tip:
settimeoutmatters more than anything else. Without it, one unresponsive port can hang your scan for a minute. With it, a closed port fails fast and the whole scan flies.
Why it's slow (and what's next)
This scanner checks one port at a time, waiting for each. Against 1,000 ports that's painfully slow — in the next lesson you'll make it dozens of times faster with threads, and have it report what each open service is.