Loop not working in socket.connect_ex()
伙计们,我正在尝试一个简单的端口扫描程序来验证端口是打开还是关闭使用
我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) iplst = ['193.169.10.100', '193.169.10.101'] ports = [80, 80] for i,j in zip(iplst,ports): result = sock.connect_ex((i,j)) if result == 0: print("open" , i) elif result != 0: print("closed", i) |
OUTPUT:
1 2 | open 193.169.10.100 closed 193.169.10.101 |
但我敢肯定,这两个端口都是开放的
您需要为每个(IP,端口)创建一个新套接字:
1 2 3 4 5 6 7 8 9 10 | import socket ips = ['193.169.10.100', '193.169.10.101'] ports = [80, 80] for ip, port in zip(ips, ports): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((ip, port)) sock.close() assert result == 0 |
一旦完成,关闭套接字也是一个好习惯。