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

4
  • 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. Commented Apr 27, 2017 at 9:06
  • 1
    I think you need one socket per (IP, port) - move creating socket inside the for loop Commented Apr 27, 2017 at 9: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). Commented Apr 27, 2017 at 9:16
  • Thank you guys for your help, I get it now Commented Apr 27, 2017 at 12:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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 stackoverflow.com/questions/5142418/… for assert explanation.
What a wonderful answer! Seems like a blessing after spending two hours searching for an answer! Only if there was like +10 in stackoverflow!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.