import socket
target = "example.com"
def scan_port(host, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
sock.connect((host, port))
sock.close()
return True
except (socket.timeout, ConnectionRefusedError):
return False
for port in range(1, 1025): # Scan common ports
if scan_port(target, port):
print(f"Port {port} is open")
This code attempts to connect to each port in the range 1 to 1024. If the connection is successful, it prints that the port is open.