2014-10-05 15:44:31 -06:00
|
|
|
.. _example_reverse_lookup:
|
|
|
|
|
|
|
|
Reverse DNS lookup
|
2017-06-16 04:16:05 -06:00
|
|
|
==================
|
2014-10-05 15:44:31 -06:00
|
|
|
|
2017-06-16 04:16:05 -06:00
|
|
|
Reverse DNS lookup involves determining the hostname associated with a given IP
|
|
|
|
address.
|
2014-10-05 15:44:31 -06:00
|
|
|
This example shows how reverse lookup can be done using unbound module.
|
|
|
|
|
|
|
|
For the reverse DNS records, the special domain in-addr.arpa is reserved.
|
2017-06-16 04:16:05 -06:00
|
|
|
For example, a host name for the IP address ``74.125.43.147`` can be obtained
|
|
|
|
by issuing a DNS query for the PTR record for address
|
|
|
|
``147.43.125.74.in-addr.arpa.``
|
|
|
|
|
|
|
|
Source code
|
|
|
|
-----------
|
2014-10-05 15:44:31 -06:00
|
|
|
|
|
|
|
::
|
|
|
|
|
2017-06-16 04:16:05 -06:00
|
|
|
#!/usr/bin/python
|
|
|
|
import unbound
|
2014-10-05 15:44:31 -06:00
|
|
|
|
2017-06-16 04:16:05 -06:00
|
|
|
ctx = unbound.ub_ctx()
|
|
|
|
ctx.resolvconf("/etc/resolv.conf")
|
2014-10-05 15:44:31 -06:00
|
|
|
|
2017-06-16 04:16:05 -06:00
|
|
|
status, result = ctx.resolve(unbound.reverse("74.125.43.147") + ".in-addr.arpa.", unbound.RR_TYPE_PTR, unbound.RR_CLASS_IN)
|
|
|
|
if status == 0 and result.havedata:
|
|
|
|
print "Result.data:", result.data.domain_list
|
|
|
|
elif status != 0:
|
|
|
|
print "Resolve error:", unbound.ub_strerror(status)
|
|
|
|
|
|
|
|
In order to simplify the python code, unbound module contains the
|
|
|
|
:meth:`unbound.reverse` function which reverses the hostname components.
|
|
|
|
This function is defined as follows::
|
2014-10-05 15:44:31 -06:00
|
|
|
|
2017-06-16 04:16:05 -06:00
|
|
|
def reverse(domain):
|
|
|
|
return '.'.join([a for a in domain.split(".")][::-1])
|