import socket


def get_hostname_by_addr(addr, success_required=True):
    """ Resolve the hostname for an ip address. If success is required, raise an exception if a hostname cannot
    be resolved for the address.
    Returns the hostname resolved for the address.
    If success is not required, returns None for addresses that do not resolve to hostnames.
    """
    try:
        return socket.gethostbyaddr(addr)[0]
    except Exception as ex:
        # if we need to succeed, just re-raise
        if success_required:
            raise
    return None