How to DNS query specific nameservers in Python

In networking, you sometimes need to resolve a hostname using a specific nameserver, be it for testing purposes or because some hostnames are only resolveable internally.

This can be done using dnspython which you can install usingĀ pip3 install dnspython.

The following example illustrates the easiest way of performing a query.

import dns.resolver

def dns_query_specific_nameserver(query="", nameserver="", qtype="A"):
    Query a specific nameserver for:
    - An IPv4 address for a given hostname (qtype="A")
    - An IPv6 address for a given hostname (qtype="AAAA")
    Returns the IP address as a string
    resolver = dns.resolver.Resolver(configure=False)
    resolver.nameservers = [nameserver]
    answer = resolver.resolve(query, qtype)

    if len(answer) == 0:
        return None
        return str(answer[0])
# NOTE: May throw dns.resolver.NXDOMAIN, dns.resolver.NoAnswer or similar

# IPv4 Usage example
dns_query_specific_nameserver(qtype="A") # e.g. ''
# IPv6 usage example
dns_query_specific_nameserver(qtype="AAAA") # e.g. '2606:4700:3035::ac43:a6d3'