Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

How to Scan Open Ports on a Host with Python

A Python function that uses socket.connect_ex to check for open TCP ports on a given host within a range and returns a list of open ports.

Medium Python 3.9+ Jun 27, 2026 Automation & scripting 1 views 0 copies

Python code

22 lines
Python 3.9+
import socket

def scan_ports(host, start_port, end_port):
    open_ports = []
    for port in range(start_port, end_port + 1):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(0.5)
        result = sock.connect_ex((host, port))
        if result == 0:
            open_ports.append(port)
        sock.close()
    return open_ports

if __name__ == "__main__":
    target_host = "localhost"
    start_port = 1
    end_port = 1024
    ports = scan_ports(target_host, start_port, end_port)
    if ports:
        print(f"Open ports on {target_host}: {ports}")
    else:
        print(f"No open ports found on {target_host} in range {start_port}-{end_port}.")

Output

stdout
Open ports on localhost: [80, 443]

How it works

The socket.connect_ex method returns an error indicator — 0 means the connection succeeded, indicating the port is open. A short timeout (0.5 seconds) keeps the scan fast. The function iterates over every port in the range, creating a new socket each time, which is simple but not optimized for speed. Using AF_INET and SOCK_STREAM specifies an IPv4 TCP connection. After each check the socket is closed to free system resources.

Common mistakes

  • Forgetting to set a timeout, which can cause the script to hang on unresponsive ports
  • Not closing the socket after each attempt, leading to resource leaks
  • Assuming a refused connection always means the port is closed (some services reject without SYN-ACK)
  • Using a too-large port range without any parallelism, making the scan very slow

Variations

  1. Use `socket.setdefaulttimeout(0.5)` globally instead of per-socket timeout
  2. Implement threading or asyncio to scan multiple ports in parallel for faster results

Real-world use cases

  • Security audits: quick internal network scans to discover unexpected open ports.
  • DevOps health checks: verify that expected services (e.g., SSH, HTTP) are reachable from a monitoring box.
  • Pentesting scripts: map attack surface before manual testing in a controlled environment.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.