def _is_valid_target()

in ec2instanceconnectcli/input_parser.py [0:0]


def _is_valid_target(hostname):
    """
    Validates if the provided "hostname" is a valid DNS name or IP address

    :param hostname: FQDN to validate
    :type hostname: basestring
    :return: Whether the given hostname is a valid DNS name or IP address
    :rtype: bool
    """
    if not hostname:
        return False

    # Check if it's a valid IP
    if _is_valid_ipv4_address(hostname) or _is_valid_ipv6_address(hostname):
        return True

    # Check if it's a valid DNS name

    if hostname[-1] == '.':
        hostname = hostname[:-1] # strip exactly one dot from the right, if present
    if len(hostname) < 1 or len(hostname) > 253: # Technically 255 octets but 2 are used for encoding
        return False

    labels = hostname.split(".")

    # the TLD must be not all-numeric
    if re.match(r"[0-9]+$", labels[-1]):
        return False

    allowed = re.compile(r"(?!-)[a-z0-9-]{1,63}(?<!-)$", re.IGNORECASE)
    return all(allowed.match(label) for label in labels)