In today’s digital world, the increase in cyber threats has led to the creation of the term ethical hacking, which means the locating of weaknesses in computer systems, networks, or applications.
In this tutorial, we are going to create an open ports scanner in Python using “the socket binding method“. This code can be categorized as ethical hacking since we will be scanning for open ports which can be considered as vulnerabilities in the system.
Let’s get started!
Table of Contents
- Disclaimer
- Imports
- Defining the scan_ports Function
- Getting the IP address of the Target Host
- Creating an Empty List to Store Open Ports
- Looping Through Ports
- Creating a Socket and Attempting to Bind it
- Handling Exceptions for Failed Binding Attempts
- Returning the List of Open Ports
- Defining the Main Function
- Displaying the Results
- Running the Main Function
- Example
- Full Code
Disclaimer
Please note: Before we proceed with this code, I must warn you not to use this code illegally or without consent since it is for educational purposes only.
PS: An open port means that there is a program or a service that is running on our device which can be dangerous because of the risk of monitoring.
Imports
First, we import the socket module that allows us to communicate with different devices over a network by creating a socket.
import socket
Defining the scan_ports Function
Next, we define this function that is responsible for taking what we designed as target_host
to scan for open ports.
def scan_ports(target_host):
Getting the IP address of the Target Host
Now, to scan for open ports, we need the IP address of the target host. socket.gethostbyname()
will convert the user-input target_host
into its IP address, If this conversion is not possible, a message indicating the failure will be printed.
try:
target_ip = socket.gethostbyname(target_host)
except socket.gaierror:
print("Could not find IP address for the hostname.")
return []
Creating an Empty List to Store Open Ports
Following that, we create an empty list that will store every open port to be found during the scan.
open_ports = []
Looping Through Ports
To ensure our port scanning is efficient, we limit our scan to the range of 1
to 1024
(or a range of your choice). Without setting a limit, scanning all ports would be significantly time-consuming.
for target_port in range(1, 1025):
Creating a Socket and Attempting to Bind it
Then we create this code that determines which port is open. To Do that we create a communication channel to the ports by creating a TCP socket (Transmission Control Protocol) and try to bind it to the specific ports (within range). If the communication (binding) is successful it means that the port is open.
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((target_ip, target_port))
sock.close()
Handling Exceptions for Failed Binding Attempts
However, if the binding is unsuccessful, it indicates that the port is closed. Consequently, this port number is not added to the list of open ports (which is generated by the subsequent code), and the function proceeds to scan the next port.
except socket.error:
open_ports.append(target_port)
print("open port", target_port)
Returning the List of Open Ports
As we said above, this part of the code will form a list of open ports after the scan_ports
function is done scanning, then it will return it to the main function.
return open_ports
Defining the Main Function
Now we define the main function that allows the user to input the target_host
he wants to scan for open ports.
def main():
target_host = input("Please enter the target host to scan: ")
open_ports = scan_ports(target_host)
Displaying the Results
After forming and returning the list of open ports to the main function, the code below displays it. If there are no open ports, the code will display a “None” message.
print("Open ports:")
if open_ports:
print(open_ports)
else:
print("None")
Running the Main Function
This part of the code makes sure that the script is run directly, and not imported as a module.
if __name__ == "__main__":
main()
Example
Full Code
import socket
def scan_ports(target_host):
try:
target_ip = socket.gethostbyname(target_host)
except socket.gaierror:
print("Could not find IP address for the hostname.")
return []
open_ports = []
for target_port in range(1, 1025):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((target_ip, target_port))
sock.close()
except socket.error:
open_ports.append(target_port)
print("open port", target_port)
return open_ports
def main():
target_host = input("Please enter the target host to scan: ")
open_ports = scan_ports(target_host)
print("Open ports:")
if open_ports:
print(open_ports)
else:
print("None")
if __name__ == "__main__":
main()
Happy Coding!