import random
import socket


def find_unbound_port(start=None,
                      increment=False,
                      port_range=(10000, 50000),
                      verbose=False,
                      logger=None):
    """
    Find a unbound port.

    Parameters
    ----------
    start : int
        The port number to start with. If this port is unbounded, return this port.
        If None, start will be a random port.
    increment : bool
        If True, find port by incrementing start port; else, random search.
    port_range : tuple
        The range of port for random number generation
    verbose : bool
        Verbose flag for logging
    logger: logging.Logger
    """
    while True:
        if not start:
            start = random.randint(*port_range)

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.bind(("127.0.0.1", start))
            # Make sure we clean up after binding
            del sock
            return start
        except socket.error as e:
            if verbose and logger:
                logger.info("Socket error: {}".format(e))
                logger.info(
                    "randomly generated port %d is bound. Trying again." %
                    start)

        if increment:
            start += 1
        else:
            start = random.randint(*port_range)