0

The title says it all. The loop takes forever for the first port and then the rest of them only take one second.

import socket
target = "192.168.0.104"


try:
    for port in range(52,85):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(1)
        result=s.connect_ex((target,port))
        if result == 0:
            print("Port {} is open".format(port))
        else:
            print("Port {} is closed".format(port))
        s.close()
        # break

except KeyboardInterrupt:
    print ('you stopp it manually')

except socket.gaierror:
    print ("Cant resolve host name")
2
  • Try starting at port 53 to find out of it is specific to port 52. Commented Dec 11, 2021 at 13:02
  • Call setdefaulttimeout before creating the first socket object, it only affects sockets created after it is called Commented Dec 11, 2021 at 13:03

1 Answer 1

3
for port in range(52,85):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.setdefaulttimeout(1)
    ...

You first create the socket, then call socket.setdefaulttimeout. But from the documentation:

socket.setdefaulttimeout(timeout)
Set the default timeout in seconds (float) for new socket objects. When the socket module is first imported, the default is None. See settimeout() for possible values and their respective meanings.

Thus, the first socket you create is not affected from the default timeout, since you set it after the socket creation. That's why it takes that long.

Apart from that it does not make much sense to call socket.setdefaulttimeout again and again with the same value. Since the new setting will affect all newly created sockets it is sufficient to call it once before any socket gets created, i.e.

socket.setdefaulttimeout(1)
for port in range(52,85):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ...
Sign up to request clarification or add additional context in comments.

Comments

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.