Skip to content

Instantly share code, notes, and snippets.

Created October 20, 2014 05:08
What would you like to do?
import socket
create_socket = lambda: socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
target_port = 49400 # Any port in the ephemeral port range that no process on your machine is using.
port = 0
# Create and bind sockets, working our way through the ephemeral port space, until we get close to our target.
while not (target_port - 5 < port < target_port):
sock = create_socket()
sock.bind(('', 0))
host, port = sock.getsockname()
print("Skipping port {}...".format(port))
# For the last few ports, try to connect to the target port.
# On Mac OS X 10.10 (14A389), I get: Unable to connect to port 49400, used local port 49400: [Errno 22] Invalid argument
# On Windows 8.1 (6.3.9600.17328), I get: Connected to port 49400, used local port 49400
while port < target_port:
sock = create_socket()
sock.connect(('', target_port))
host, port = sock.getsockname()
print("Connected to port {}, used local port {}".format(target_port, port))
except socket.error as e:
host, port = sock.getsockname()
print("Unable to connect to port {}, used local port {}: {}".format(target_port, port, e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment