In addition to setting the socket timeout, you can also use a multi-threaded technique to speed up the process. At best, it will be N times faster if you have N ports to scan.
# This script runs on Python 3 import socket, threading def TCP_connect(ip, port_number, delay, output): TCPsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) TCPsock.settimeout(delay) try: TCPsock.connect((ip, port_number)) output[port_number] = 'Listening' except: output[port_number] = '' def scan_ports(host_ip, delay): threads = []
source share