1

Using the dnspython library, I have this simple code, given the DNS IP, I canquery a domain name. I need to get the zone name of the DNS server. For example, if instead of 8.8.8.8 I have a private IP 192.168.4.5 for zone named com and the server in question is a.com.

How can I get the com as a result of a query for my zone's DNS IP?

import dns.resolver

resolver = dns.resolver.Resolver()
resolver.nameservers = ['8.8.8.8']

def myQuery(domain, records):
    for r in records:
        try:
            response = resolver.query(domain, r)
            for rData in response:
                    domainIP = str(rData)
                    print(domainIP)
                    break # we only need one IP
        except Exception as e:
            print(e)

myQuery("google.com","A")
user9371654
  • 2,160
  • 16
  • 45
  • 78

1 Answers1

4

It sounds like you're after a reverse IP lookup.

You have the IP but you want the name. If so, you're looking for a PTR type record (https://en.wikipedia.org/wiki/Reverse_DNS_lookup). PTR records look like this:

5.4.168.192.in-addr.arpa.

You don't have to know that as there's a dns-python helper function called reversername that will generate those names from an IP address for you. Here's an example of a reverse IP lookup of 8.8.8.8:

>>> from dns import reversename, resolver
>>> 
>>> rev_name = reversename.from_address('8.8.8.8')
>>> reversed_dns = str(resolver.query(rev_name,"PTR")[0])
>>> print reversed_dns
google-public-dns-a.google.com.

In order to get it to work on your private server, you need to make sure either you or your system is adding/creating PTR records when registering your machines with DNS. Assuming you have PTR records in your DNS then this should work for you:

from dns import reversename, resolver
rev_name = reversename.from_address('192.168.4.5')
reversed_dns = str(resolver.query(rev_name,"PTR")[0])
print(reversed_dns)
clockwatcher
  • 3,193
  • 13
  • 13
  • I get this error: `Original exception was: Traceback (most recent call last): File "simple-test.py", line 3, in reversed_dns = str(resolver.query(rev_name,"PTR")[0]) File "/usr/local/bin/code/myclient/dns/resolver.py", line 1132, in query raise_on_no_answer, source_port) File "/usr/local/bin/code/myclient/dns/resolver.py", line 1051, in query raise NXDOMAIN(qnames=qnames_to_try, responses=nxdomain_responses) dns.resolver.NXDOMAIN: The DNS query name does not exist: 3.56.168.192.in-addr.arpa.` – user9371654 Jun 02 '18 at 05:40
  • 1
    That indicates that the DNS server you're querying doesn't have a PTR record for that IP. As I mentioned, in order for this to work, you need to make sure you have PTR records created in the in-addr.arpa zone of your DNS server. – clockwatcher Jun 02 '18 at 07:45