Python › Module 2 › Lesson 4
Lab — Build a Port Scanner
Build and run a localhost-only port scanner with copy-paste Python you can extend
Opening
Lab rule: 127.0.0.1 only
Build a tiny scanner and point it at localhost. Do not change the host to the public internet for this exercise.
1. port_scan.py
Localhost TCP connect scanner — copy & runimport socket HOST = "127.0.0.1" # lab only PORTS = [22, 80, 443, 3306, 8080] TIMEOUT = 0.5 def is_open(host, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(TIMEOUT) try: s.connect((host, port)) return True except OSError: return False finally: s.close() print(f"Scanning {HOST} ...") for port in PORTS: state = "OPEN" if is_open(HOST, port) else "closed" print(f"{port:5} {state}")
import socket
HOST = "127.0.0.1" # lab only
PORTS = [22, 80, 443, 3306, 8080]
TIMEOUT = 0.5
def is_open(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TIMEOUT)
try:
s.connect((host, port))
return True
except OSError:
return False
finally:
s.close()
print(f"Scanning {HOST} ...")
for port in PORTS:
state = "OPEN" if is_open(HOST, port) else "closed"
print(f"{port:5} {state}")2. Run
Executepython port_scan.py python3 port_scan.py
python port_scan.py python3 port_scan.py
OPEN means something on your machine accepted TCP on that port. closed/filtered means connect failed. Challenge: wrap argparse so HOST defaults to 127.0.0.1 and refuses other hosts until you remove a SAFETY flag.
Complete port scanner lab
Save port_scan.py, run it against 127.0.0.1, and note which ports report OPEN on your system.
Knowledge Check
Why keep HOST = "127.0.0.1" in this lab?
Multiple choice
Knowledge Check
True or False: is_open() returning True means connect() succeeded.
True or False