A Simple Port Scanner Using Python
Introduction-
A port scanner is a crucial tool for network security professionals and enthusiasts. It allows you to discover open, closed, or filtered ports on a target system. In this tutorial, we’ll create a basic port scanner using Python.
Prerequisites-
Before we dive into the code, ensure you have Python installed on your system. You can download it from the official Python website (https://www.python.org/downloads/).
Code Implementation-
Below is the Python code for our simple port scanner:
- Import the Socket Library:
import socket2. Define the Port Scanner Function:
def scan_ports(host_port, start_port, end_port):
print(f"Scanning ports on {host_port}...")
for port in range(start_port, end_port + 1):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1) # Set a connection timeout
result = sock.connect_ex((host_port, port))
if result == 0:
print(f"Port {port} is open")
sock.close()3. Gather User Input and Initiate Scanning:
if __name__ == "__main__":
target_hosts = input("Enter the host IP address: ")
start_port = int(input("Enter the starting port: "))
end_port = int(input("Enter the ending port: "))
scan_ports(target_hosts, start_port, end_port)Get CyberwizD’s stories in your inbox
Join Medium for free to get updates from this writer.
Explanation-
- We create a function called
scan_portsthat takes the target host (IP address), starting port, and ending port as arguments. - Inside the function, we use a
forloop to iterate through the specified port range. - For each port, we create a socket and attempt to connect to it using
sock.connect_ex((host, port)). - If the connection result is 0 (indicating success), we print that the port is open.
- Finally, we close the socket.
Usage-
- Run the script in your terminal or IDE.
- Enter the target host’s IP address.
- Specify the starting and ending port numbers.
- The script will scan the specified ports and display the results.
Conclusion-
This simple port scanner provides a foundation for more advanced network scanning tools. Remember to use it responsibly and only on systems you have permission to scan.









