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!