Reverse DNS lookup

Reverse DNS lookup involves determining the hostname associated with a given IP address. This example shows how reverse lookup can be done using unbound module.

For the reverse DNS records, the special domain is reserved. For example, a host name for the IP address can be obtained by issuing a DNS query for the PTR record for address

Source code

import unbound

ctx = unbound.ub_ctx()

status, result = ctx.resolve(unbound.reverse("") + "", unbound.RR_TYPE_PTR, unbound.RR_CLASS_IN)
if status == 0 and result.havedata:
    print "",
elif status != 0:
    print "Resolve error:", unbound.ub_strerror(status)

In order to simplify the python code, unbound module contains the unbound.reverse() function which reverses the hostname components. This function is defined as follows:

def reverse(domain):
    return '.'.join([a for a in domain.split(".")][::-1])