import re


def is_valid_hostname(hostname):
    """
    Takes a hostname and tries to determine if it is valid or not

    Args:
        hostname: String of the hostname to check

    Returns:
        Boolean if it is valid or not
    """
    # Borrowed from https://stackoverflow.com/questions/2532053/validate-a-hostname-string
    if len(hostname) > 255:
        return False
    if hostname == 'localhost':
        return True
    if hostname.endswith("."): # A single trailing dot is legal
        hostname = hostname[:-1] # strip exactly one dot from the right, if present
    disallowed = re.compile(r"[^A-Z\d-]", re.IGNORECASE)
    return all( # Split by labels and verify individually
        (label and len(label) <= 63 # length is within proper range
         and not label.startswith("-") and not label.endswith("-") # no bordering hyphens
         and not disallowed.search(label)) # contains only legal characters
        for label in hostname.split("."))