<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def get_hostname(address, fqdn=True):
 """ Resolves hostname for given IP, or returns the input if it is already a hostname. """

    if is_ip(address):
        try:
            import dns.reversename
        except ImportError:
            if six.PY2:
                apt_install("python-dnspython", fatal=True)
            else:
                apt_install("python3-dnspython", fatal=True)
            import dns.reversename

        rev = dns.reversename.from_address(address)
        result = ns_query(rev)

        if not result:
            try:
                result = socket.gethostbyaddr(address)[0]
            except Exception:
                return None
    else:
        result = address

    if fqdn:
        # strip trailing .
        if result.endswith('.'):
            return result[:-1]
        else:
            return result
    else:
        return result.split('.')[0]