C

Python › Module 2 › Lesson 4

BeginnerModule 2Lesson 4/5

Lab — Build a Port Scanner

Build and run a localhost-only port scanner with copy-paste Python you can extend

25 min+53 XP2 quiz
Module progress4 of 5

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

1

Why keep HOST = "127.0.0.1" in this lab?

Multiple choice

Knowledge Check

2

True or False: is_open() returning True means connect() succeeded.

True or False

← Previous

Answer all 2 knowledge checks to continue. (0/2 answered)