Search code examples
pythonsocketsdnsdnspython

How to get multiple records in one DNS query


This simple code snippet using dnspython the code resolves the name to IP.

In this example, the domain is google.com and the answer for A record. How can I get multiple records (e.g. TXT, CNAME, ..) in one query?

from dns.resolver import dns

myResolver = dns.resolver.Resolver() #create a new instance named 'myResolver'
myAnswers = myResolver.query("google.com", "A") #Lookup the 'A' record(s) for google.com
for rdata in myAnswers: #for each response
    print (rdata) #print the data

Solution

  • I don't think there's an "any" option. This is probably because of the security implications of DNS reflection attacks and DNS queries over UDP. Probably best to use a list like 'types' below:

    import dns.resolver
    
    def get_domain():
        types=[
            'A',
            'TXT',
            'CNAME',
            'NS',
        ]
        for type in types:
            try: 
                reponse = dns.resolver.query('domain.com', type)
                for data in response:
                    print (type, "-", data.to_text())
                except Exception as err:
                    print(err)
    
    if __name__ == '__main__':
        get_domain('stackoverflow.com')
    

    There's a lot of security around DNS queries now because of the proliferation of DNS reflection DDoS attacks so you may want to rate limit your code. Especially if you're running this against multiple domains