In this very short article I’ll present a simple port scanner written in Python.

If you’re looking for a production ready, kick-ass port scanner, I highly recommend nmap.

For those unfamiliar with port scans;

When performing a port scan, you are in reality probing a server or a host for open ports.
Said in other words, a port scan determines which ports on a given server or host are open, and which ones are closed.
An analogy to the real world can be seen as knocking on doors, and determining which are open.

I promised that this article would be short, so let’s jump straight to the port scanner. The comments explains the flow of the script.


import socket as so
import subprocess as sp
import sys

# Determining if user enters domain or IP

def queryDomain():
    while True:
        ipDom = raw_input("Scan IP or domain(i/d)? > ")
        if ipDom == 'd':
            return True
        if ipDom == 'i':
            return False

# Removing all content on the screen'clear', shell=True)

# Obtaining IP-address, storing in variable 'ipToScan'
# If the user enter a domain name, the IP is resolved from the domain name
if queryDomain():
    domain = raw_input("Enter domain name > ")
        ipToScan = so.gethostbyname(domain)
        print("IP of " + domain + " is " + ipToScan)
        print("Unknown hostname " + domain)
    ipToScan = raw_input("Enter IP to scan > ")

# Obtaining min and max port to scan
while True:
    minPort = input("Enter min port to scan > ")
    maxPort = input("Enter max port to scan > ")
    if minPort <= maxPort:
    print("Min port must be <= max port")

# Header
print "*" * 50
print "Executing scan... Please wait"
print "*" * 50

# Executing scan
for port in range(minPort, maxPort + 1):
    s = so.socket(so.AF_INET, so.SOCK_STREAM)
    if not s.connect_ex((ipToScan, port)):
        print "Port {}: Open".format(port)

That’s it.
Simply run the script by typing python in your terminal.