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.
Python code
22 linesimport 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
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
- Use `socket.setdefaulttimeout(0.5)` globally instead of per-socket timeout
- 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
More from Automation & scripting
- Batch Rename Hundreds of Files in Python easy
- Build a Command-Line Password Generator in Python easy
- Build a Complete Web Scraper with Requests and BeautifulSoup in Python medium
- Build a Network Ping Monitor in Python medium
- Create a Local Search Engine to Instantly Find Files on Your Computer in Python medium
- Create a Simple HTTP File Server in Python easy
Keep learning
Related tutorials and quizzes for this topic.