Sitemap

A Simple Port Scanner Using Python

2 min readFeb 3, 2024

--

Press enter or click to view image in full size

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:

  1. Import the Socket Library:
import socket

2. 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_ports that takes the target host (IP address), starting port, and ending port as arguments.
  • Inside the function, we use a for loop 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-

  1. Run the script in your terminal or IDE.
  2. Enter the target host’s IP address.
  3. Specify the starting and ending port numbers.
  4. 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.

Feel free to share this tutorial with your cybersecurity community or any other platform. Happy scanning! 🚀🔍

--

--

CyberwizD
CyberwizD

Written by CyberwizD

Computer Hacker (Proficient in Python) | Network and Web Application Security