In this blogs we will discuss about a basic scanning program to find open ports on host or target machine.
We have to make use of socket module and socket.connect_ex() function to create a basic scan program to find open ports on a host machine. socket.connect_ex() takes IP address and port as the parameters.
socket.connect_ex() function returns zero if found open port otherwise returns errno (10060/10061). We can make use of this function to scan open ports on a target machine.
In the below code, we have a define list of ports to scan for google.com url.
Step 1 Import Socket Module
Step 2 Determine host ip address
Step 3 Create a list of ports to scan
Step 4 Use socket.connect_ex() function to scan ports
Step 5 Displaying the result. If result = 0 , display ‘Port is open’. If result is either 10060 or 10061, display ‘Port is closed’.
import socket url = 'google.com' host = socket.gethostbyname(url) list = [22,30,80,443,445,787] for port in list: s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) result = s.connect_ex((host,port)) print(result) if result == 0: print('Port %s is open'%port) else: print('Port %s is closed'%port) s.close()
Output
10060
Port 22 is closed
10060
Port 30 is closed
0
Port 80 is open
0
Port 443 is open
10061
Port 445 is closed
10060
Port 787 is closed