5

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

Sundararajan
  • 544
  • 2
  • 9
  • 25
  • 1
    One thing would be to `close` the socket after a successful `connect` (`connect_ex`). Check `connect_ex` return code (that contains the `errno` value) which will probably be something like _Already connected_. – CristiFati Apr 27 '17 at 09:06
  • 1
    I think you need one socket per (IP, port) - move creating socket inside the `for` loop – matino Apr 27 '17 at 09:13
  • 1
    @matino is right, sorry for the confusion, after closing the socket its descriptor becomes invalid. You need to create a new socket for each (successful) connection (don't forget to close it when done). – CristiFati Apr 27 '17 at 09:16
  • Thank you guys for your help, I get it now – Sundararajan Apr 27 '17 at 12:56

1 Answers1

8

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.

matino
  • 17,199
  • 8
  • 49
  • 58
  • Now i get it why my code didn't work, I forgot to close the socket, Can you explain me what `assert result == 0` does. – Sundararajan Apr 27 '17 at 09:53
  • 1
    Your code didn't work because you were using the same sockets for different addresses. Once you close the socket, you can't reuse it (calling `connect_ex` will raise an error). Check http://stackoverflow.com/questions/5142418/what-is-the-use-of-assert-in-python for assert explanation. – matino Apr 27 '17 at 10:33
  • 1
    What a wonderful answer! Seems like a blessing after spending two hours searching for an answer! Only if there was like +10 in stackoverflow! – Ali Abbas Jaffri Dec 24 '17 at 13:14