title: Python socket connect() vs. connect_ex()
body: <p>I would like to take a look at those 2 functions in Python. I did some research and bumped into something like this:</p>
  
  <blockquote>
    <p>socket.connect_ex(address)</p>
    
    <p>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.</p>
  </blockquote>
  
  <p>I totally get this. I wrote a simple port scanner to test efficiency and got interesting results:</p>
  
  <pre><code>[*] 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
  </code></pre>
  
  <p>So, <code>connect_ex</code> seems to be twice as efficient as <code>connect</code>. If it comes to syntax the only difference is that with <code>connect</code> you surround it by <code>try except</code> and catch an error when it fails to connect and with <code>connect_ex</code> you check the result for being 0 or errno. That is all clear but my question is why <code>connect_ex</code> works faster than <code>connect</code>? What reason is down there causing such behaviour?</p>