查看多个ip加端口是否可以连接
import socket def check_port(ip, port, timeout=1): """ 尝试连接指定IP和端口,返回True如果端口开放,False则表示连接失败。 """ try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) result = sock.connect_ex((ip, port)) sock.close() return result == 0 except socket.error as e: print(f"Socket error: {e}") return False def scan_ips(start_ip, end_ip, port): """ 扫描指定IP范围内的指定端口是否开放。 """ for i in range(int(start_ip.split('.')[-1]), int(end_ip.split('.')[-1]) + 1): ip = f"192.168.1.{i}" if check_port(ip, port): print(f"{ip}:{port} is open.") else: print(f"{ip}:{port} is not accessible.") if __name__ == "__main__": start_ip = "192.168.1.200" end_ip = "192.168.1.255" port = 5000 scan_ips(start_ip, end_ip, port)