Programming a Port Scanner in Python

Posted: May 26, 2012 in Programming, Python, Socket Programming
Tags: , ,

The basic idea to check if a port is open is to connect to the host at that particular port and if the connection was successful , then it means the port at which we tried to connect is open otherwise it is not open.

The first thing we do is to ask the user the IP address and the range of ports we need to scan (Alternatively you can predefine them in the source). Then we create a loop within the range of the given ports, and for each value of the port in the loop we try to connect to the current value port at the specified host, and if the connection was successful, we print that that particular port is open. And after every check we close the created socket.

# Port Scanner
# https://extr3metech.wordpress.com
from socket import *                          # Imports socket module
ip=raw_input("Enter IP to scan : ")           # Asks user to enter IP address
start=input("Enter starting port number : ")  # Asks user to enter starting port number
end=input("Enter ending port number : ")      # Asks user to enter ending port number
print "Scanning IP: " , ip
for port in range(start,end):                 # For loop from starting to ending port
    s=socket(AF_INET, SOCK_STREAM)            # Creates a socket s
    if(s.connect_ex((ip,port))==0):           # If connection to port was successful,then returns 0
        print "Port " , port, "is open"       # Prints open port
    s.close()                                 # Closes socket s
print "Scanning completed !! "

If you have any sort of queries , feel free to ask. Thank you! Happy Coding!

ΞXΤЯ3МΞ

Comments
  1. Eldon Nelson says:

    This was a great post and allowed me to figure out the port of the license server I needed to access without the use of nmap (which I could not run without root access on the machine I was using). Great article! I reference your Python script above and you blog at the post below; I use it to figure out what ports I needed to forward for a service.

    Thanks!

    Accessing Mentor FlexLM License Server Via SSH Port Forwarding
    http://tenthousandfailures.com/blog/2014/2/1/accessing-mentor-flexlm-license-server-via-ssh-port-forwarding

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s