In this tutorial, we will use an example to show you how to create a port scanner using python socket.
1.Import library
import socket import threading
2.Set the target host
target = "127.0.0.1" # scan local host
3.Define a function to print opened port
def port_scanner(port): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((target, port)) print(f"Port {port} is open") except: pass
In this example code, we use socket to scan the host port and print the opened one.
4.Scan port using thread
for port in range(1,5051): thread = threading.Thread(target =port_scanner, args=[port]) thread.start()
Run this code, you may get these opened ports:
Port 21 is open Port 80 is open Port 135 is open Port 443 is open Port 445 is open Port 3306 is open Port 5040 is open