Parse hostname string and return a tuple of (host, port)
    If port missing in hostname string then use default_port
    If anything is not a valid then return None

    hostname should contain a host and an option space delimited port
    host port

    As an attempt to prevent foolish mistakes the parser also tries to identify
    the port when it is colon delimited not space delimited. As in host:port.
    This is problematic since IPV6 addresses may have colons in them.
    Consequently the use of colon delimited ports is strongly discouraged.
    An ipv6 address must have at least 2 colons.

def parse_hostname(hostname, default_port):
    '''
    Parse hostname string and return a tuple of (host, port)
    If port missing in hostname string then use default_port
    If anything is not a valid then return None

    hostname should contain a host and an option space delimited port
    host port

    As an attempt to prevent foolish mistakes the parser also tries to identify
    the port when it is colon delimited not space delimited. As in host:port.
    This is problematic since IPV6 addresses may have colons in them.
    Consequently the use of colon delimited ports is strongly discouraged.
    An ipv6 address must have at least 2 colons.
    '''
    try:
        host, sep, port = hostname.strip().rpartition(' ')
        if not port:  # invalid nothing there
            return None

        if not host:  # no space separated port, only host as port use default port
            host = port
            port = default_port
            # ipv6 must have two or more colons
            if host.count(':') == 1:  # only one so may be using colon delimited port
                host, sep, port = host.rpartition(':')
                if not host:  # colon but not host so invalid
                    return None
                if not port:  # colon but no port so use default
                    port = default_port

        host = host.strip()
        try:
            port = int(port)
        except ValueError:
            return None

    except AttributeError:
        return None

    return (host, port)