Reputation: 704
Folks, I'm trying a simple port scanner to verify whether the port is open or closed using socket.connect_ex((192.169.10.1, 80))
It works fine but I want pass multiple IP and port so i used list and iterate them using for loop. I get result only for the first IP in the list, the second IP is not giving correct result Instead it always runs the elif block, what might be the problem? can some one guide me where I'm going wrong.
MY CODE:
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:
open 193.169.10.100
closed 193.169.10.101
But I'm sure, both ports are open
Upvotes: 5
Views: 6838
Reputation: 17725
You need to create a new socket per each (IP, port):
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
Also it's a good practise to close the socket once you're done.
Upvotes: 8