python-3.xdnsdnspython

Does DNSpython have a method that automatically performs a forward or reverse lookup depending on the value that it's passed?


I am wondering if there is a way to pass either a host, fqdn, or IP address to DNSPython and have it perform the proper lookup (forward for hosts and fqdns and reverse for ips). Also, I want to know what kind of address (host, fqdn, or ip) was sent to the method originally.

Thanks in advance


Solution

  • To my knowledge, there's not a single function that will do what you're looking for. However, it wouldn't be too hard to implement. Here's how I'd probably do it.

    First, I'd check if the input was an IP address

    import ipaddress
    
    def is_ipaddress(string):
        try:
            ipaddress.ip_address(string)
            return True
        except ValueError:
            return False
    

    If it is an IP address, then I'd call dns.query.reverse_query(). This is assuming I have installed the latest development version of dnspython from Github because reverse_query() was only recently added (see https://github.com/rthalley/dnspython/commit/7c105cce64699e1a221176f98f7cb9e682aba1e0).

    If it's not an IP address, then I'd prepare my query with dns.message.make_query(name, rdtype) and then send it with dns.query.udp().

    If you wanted to use the value of search in /etc/reolv.conf, you might consider creating a dns.resolver.Resolver, which currently does search processing by default.

    import dns.resolver
    import dns.rdatatype
    
    resolver = dns.resolver.Resolver()
    response = resolver.query('my-computer', dns.rdatatype.A)