'bind this socket to a random port in a range
If the port range is unspecified, the system will choose the port.
Parameters
addr : str
The address string without the port to pass to ``Socket.bind()``.
min_port : int, optional
The minimum port in the range of ports to try (inclusive).
max_port : int, optional
The maximum port in the range of ports to try (exclusive).
max_tries : int, optional
The maximum number of bind attempts to make.
Returns
port : int
The port the socket was bound to.
Raises
ZMQBindError
if `max_tries` reached before successful bind'

def bind_to_random_port(self, addr, min_port=49152, max_port=65536, max_tries=100):

    if (hasattr(constants, 'LAST_ENDPOINT') and (min_port == 49152) and (max_port == 65536)):
        self.bind(('%s:*' % addr))
        url = self.last_endpoint.decode('ascii', 'replace')
        (_, port_s) = url.rsplit(':', 1)
        return int(port_s)
    for i in range(max_tries):
        try:
            port = random.randrange(min_port, max_port)
            self.bind(('%s:%s' % (addr, port)))
        except ZMQError as exception:
            en = exception.errno
            if (en == zmq.EADDRINUSE):
                continue
            elif ((sys.platform == 'win32') and (en == errno.EACCES)):
                continue
            else:
                raise
        else:
            return port
    raise ZMQBindError('Could    not    bind    socket    to    random    port.')
