How to Make a Port Scanner in Python
Published on Aug. 22, 2023, 12:15 p.m.
You can create a basic port scanner in Python using the socket
library. Here is an example:
import socket
import threading
target = 'localhost'
start_port = 1
end_port = 1024
def scan(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
try:
sock.connect((target, port))
print(f"Port {port} is open")
except:
pass
sock.close()
for port in range(start_port, end_port+1):
threading.Thread(target=scan, args=(port,)).start()
In this example, we define a scan()
function that takes a port number as an argument and tries to connect to that port on the target host. If the connection succeeds, we print a message to indicate that the port is open.
We then use a for
loop to iterate over a range of port numbers, starting from start_port
and ending at end_port
. For each port number, we create a new thread and call the scan()
function with the port number as an argument.
Using multiple threads allows us to scan multiple ports concurrently, which can significantly speed up the scanning process.
Note that this is just a basic example, and more advanced port scanning techniques may be required for certain use cases. Additionally, it’s important to note that port scanning can be used for malicious purposes and should only be performed on systems that you are authorized to scan.