This is a logical error in your code.
First of all, only newer versions of Windows use 5000-65534 as ephemeral ports. In older versions, 1025-5000 was used instead.
You create several sockets that are explicitly tied to random ephemeral ports until you have connected a socket that is 10 ports smaller than your target port. However, if any of these sockets is actually bound to the actual target port, you ignore this and continue the loop. That way, you can or can get the socket bound to the target port, and you can or can't get the final port value, which is actually smaller than the target port.
After that, if port turns out to be smaller than your target port (which is not guaranteed), then you create more sockets that are implicitly tied to various random available ephemeral ports when you call connect() (it implicitly bind() internally if bind() is not already was called), none of which will be the same ephemeral port with which you are explicitly tied, since these ports are already in use and can no longer be used.
In no case do you have any socket connecting the ephemeral port to the same ephemeral port. And if another application is not tied to your target port and is actively listening on this port, then there is no way that connect() can successfully connect to the target port on any of the created sockets, since none of them are in the listening state. And getsockname() not valid for an unconnected socket, and the connecting socket is not guaranteed to be bound if connect() fails. Thus, the symptoms that you think are occurring are actually physically impossible given the code you showed. Your journal simply makes the wrong assumptions and thus logs the wrong things, giving you a false state of being.
Try something more like this and you will see what the real ports are:
import socket TARGET_PORT = 49400 def mksocket(): return socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) while True: sock = mksocket() sock.bind(('127.0.0.1', 0)) host, port = sock.getsockname() print 'Bound to local port %d' % (port) if port > TARGET_PORT - 10 and port < TARGET_PORT: break if port >= TARGET_PORT: print 'Bound port %d exceeded target port %d' % (port, TARGET_PORT) else: while port < TARGET_PORT: sock = mksocket()