import socket import threading from queue import Queue import time # 定义要检查的IP范围和端口 IP_BASE = "192.168.10." START_IP = 1 END_IP = 255 TARGET_PORT = 5555 # 线程数量,可根据需要调整 THREAD_COUNT = 30 def check_port(ip, port, result_queue): """检查指定IP的端口是否开放""" try: # 创建socket对象 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 设置超时时间为1秒 sock.settimeout(1) # 尝试连接 result = sock.connect_ex((ip, port)) if result == 0: result_queue.put(ip) sock.close() except Exception: pass def worker(ip_queue, result_queue): """工作线程,从队列中获取IP并检查端口""" while not ip_queue.empty(): ip = ip_queue.get() check_port(ip, TARGET_PORT, result_queue) ip_queue.task_done() if __name__ == "__main__": start_time = time.time() print(f"开始扫描 {IP_BASE}{START_IP} 到 {IP_BASE}{END_IP} 的 {TARGET_PORT} 端口...") # 创建IP队列 ip_queue = Queue() for i in range(START_IP, END_IP + 1): ip = f"{IP_BASE}{i}" ip_queue.put(ip) # 创建存储开放端口IP的队列 result_queue = Queue() # 创建并启动线程 threads = [] for _ in range(THREAD_COUNT): thread = threading.Thread(target=worker, args=(ip_queue, result_queue)) thread.start() threads.append(thread) # 等待所有IP都被处理 ip_queue.join() # 收集结果 open_ips = [] while not result_queue.empty(): open_ips.append(result_queue.get()) # 排序结果 open_ips.sort(key=lambda x: int(x.split(".")[-1])) # 输出结果 print("\n扫描完成!") print(f"耗时: {time.time() - start_time:.2f} 秒") print(f"发现 {len(open_ips)} 个设备的 {TARGET_PORT} 端口开放:") for ip in open_ips: print(f" {ip}:{TARGET_PORT}")