title: Fast detection or simulation of WSAECONNREFUSED
body: <p>Windows sockets have some strange behavior when it comes to WSAECONNREFUSED (which means backlog full or port not available, see <a href="https://stackoverflow.com/a/10308338/851737">https://stackoverflow.com/a/10308338/851737</a>). If Windows detects one of these conditions, it retries (up to) two times with an interval of 0.5s. This means it takes at least 1 second to detect WSAECONNREFUSED on a socket connection attempt (<a href="http://support.microsoft.com/kb/175523/en-us" rel="nofollow noreferrer">http://support.microsoft.com/kb/175523/en-us</a>). </p>
  
  <p>Is there any way to speed up this detection without messing with the registry values? I need to simulate refusing socket connections in unittests. A workaround like simulating a refused connection with raw sockets would be acceptable, too.</p>
  
  <p>Here is a simple Python script demonstrating the issue:</p>
  
  <pre><code>import errno
  import socket
  import time
  
  PORT = 50123
  
  
  def main():
      s = socket.socket()
      s.bind(('127.0.0.1', PORT))
      s.listen(0)
      client = socket.socket()
      client.connect(('127.0.0.1', PORT))
  
      client2 = socket.socket()
      start = time.time()
  
      try:
          client2.connect(('127.0.0.1', PORT))
      except socket.error as e:
          assert e.errno == errno.WSAECONNREFUSED
          print 'connection attempt took', time.time() - start
      finally:
          client2.close()
          client.close()
          s.close()
  
  
  if __name__ == '__main__':
      main()
  </code></pre>