import six
import re


def sanitize_hostname(hostname):
    """Return a hostname which conforms to RFC-952 and RFC-1123 specs."""
    if isinstance(hostname, six.text_type):
        hostname = hostname.encode('latin-1', 'ignore')

    hostname = re.sub(b'[ _]', b'-', hostname)
    hostname = re.sub(b'[^\w.-]+', b'', hostname)
    hostname = hostname.lower()
    hostname = hostname.strip(b'.-')

    return hostname