Tools like Nmap are the standard for network scanning, but writing your own scanner is one of the best ways to understand what is actually happening on the network. In this guide you will build a small, fast port scanner with nothing but Python's standard library.
Only scan machines you own or have written permission to test. Our labs give you safe targets to practise on.
How a TCP port scan works
Every network service listens on a port. A web server usually listens on port 80 or 443, SSH on port 22. When your computer connects to a port:
- If a service is listening, the connection is accepted. The port is open.
- If nothing is listening, the target refuses the connection. The port is closed.
- If a firewall silently drops the packet, you get no answer. The port is filtered.
Our scanner tries to open a TCP connection to each port and records the ones that succeed.
Step 1: Check a single port
Python's socket module lets you open network connections directly. The connect_ex method returns 0 when the connection succeeds instead of raising an error, which makes it perfect for scanning:
import socket
def is_open(host: str, port: int) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(0.5)
return s.connect_ex((host, port)) == 0
print(is_open("127.0.0.1", 22))
The timeout matters. Without it, a filtered port could make your script wait for a long time.
Step 2: Scan many ports quickly
Checking 1,024 ports one after another is slow. Most of the time is spent waiting for answers, so we can check many ports at once using threads:
import socket
from concurrent.futures import ThreadPoolExecutor
TARGET = "127.0.0.1"
PORTS = range(1, 1025)
def scan(port: int) -> int | None:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(0.5)
if s.connect_ex((TARGET, port)) == 0:
return port
return None
with ThreadPoolExecutor(max_workers=100) as pool:
open_ports = [p for p in pool.map(scan, PORTS) if p]
print("Open ports:", open_ports)
With 100 worker threads, the scan finishes in a few seconds instead of minutes.
Step 3: Grab service banners
Many services announce themselves as soon as you connect. SSH, for example, sends a version string. Reading that banner tells you what software is running:
def grab_banner(host: str, port: int) -> str:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(2)
s.connect((host, port))
try:
return s.recv(1024).decode(errors="ignore").strip()
except socket.timeout:
return ""
Run it against an open port 22 in your lab and you will see something like SSH-2.0-OpenSSH_9.6. Version information like this is exactly what attackers look for, and what defenders need to keep up to date.
What you learned
- How TCP connections reveal open, closed and filtered ports.
- How to use the
socketmodule with timeouts. - How to speed up I/O-bound work with a thread pool.
- Why exposed version banners are a security concern.
Ideas to extend it
- Accept the target and port range as command-line arguments with
argparse. - Save results to a JSON file for your reports.
- Compare two scans and highlight newly opened ports.
Each of these is covered with guided labs in our Applied Python Programming course.
Learn this hands-on
Applied Python Programming
Write real security scripts with a guided lab for every concept.
View course