I would like to take a look at those 2 functions in Python. I did some research and bumped into something like this:
socket.connect_ex(address)
Like connect(address), but return an error indicator instead of raising an exception for errors returned by the C-level connect() call (other problems, such as “host not found,” can still raise exceptions). The error indicator is 0 if the operation succeeded, otherwise the value of the errno variable. This is useful to support, for example, asynchronous connects.
I totally get this. I wrote a simple port scanner to test efficiency and got interesting results:
[*] start scanning on host 127.0.0.1 for ports range(0, 65535) with
method(connect)
[*] method connect finished in 0:00:12.253352
[*] start scanning on host 127.0.0.1 for ports range(0, 65535) with
method(connect_ex)
[*] method connect_ex finished in 0:00:06.839319
So, connect_ex
seems to be twice as efficient as connect
. If it comes to syntax the only difference is that with connect
you surround it by try except
and catch an error when it fails to connect and with connect_ex
you check the result for being 0 or errno. That is all clear but my question is why connect_ex
works faster than connect
? What reason is down there causing such behaviour?
socket.connect(address) -> Connect to a remote socket at address. (The format of address depends on the address family — see above.)
If the connection is interrupted by a signal, the method waits until the connection completes, or raise a socket.timeout on timeout, if the signal handler doesn’t raise an exception and the socket is blocking or has a timeout. For non-blocking sockets, the method raises an InterruptedError exception if the connection is interrupted by a signal (or the exception raised by the signal handler).
Raises an auditing event socket.connect with arguments self, address.
Changed in version 3.5: The method now waits until the connection completes instead of raising an InterruptedError exception if the connection is interrupted by a signal, the signal handler doesn’t raise an exception and the socket is blocking or has a timeout (see the PEP 475 for the rationale).
socket.connect_ex(address) -> Like connect(address), but return an error indicator instead of raising an exception for errors returned by the C-level connect() call (other problems, such as “host not found,” can still raise exceptions). The error indicator is 0 if the operation succeeded, otherwise the value of the errno variable. This is useful to support, for example, asynchronous connects.
Raises an auditing event socket.connect with arguments self, address.
Ref: https://docs.python.org/3/library/socket.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With