Chapter 4 ■ SoCket NameS aNd dNS
70
Thus, let’s take a look at one of the third-party DNS libraries for Python as we bring this chapter to a close. The
best one that currently seems to be available for Python 3 is dnspython3, which you can install using the standard
Python packaging tool.
$ pip install dnspython3
The library uses its own tricks to find out what domain name servers your Windows or POSIX operating system
is currently using, and then it asks those servers to go and do recursive queries on its behalf. Thus, there is not a
single piece of code in this chapter that avoids needing a correctly configured host that an administrator or network
configuration service has already configured with working name servers.
Listing 4-2 illustrates a simple and comprehensive lookup.
Listing 4-2. A Simple DNS Query Doing Its Own Recursion
#!/usr/bin/env python3
Foundations of Python Network Programming, Third Edition
https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter04/dns_basic.py
Basic DNS query
import argparse, dns.resolver
def lookup(name):
for qtype in 'A', 'AAAA', 'CNAME', 'MX', 'NS':
answer = dns.resolver.query(name, qtype, raise_on_no_answer=False)
if answer.rrset is not None:
print(answer.rrset)
if name == 'main':
parser = argparse.ArgumentParser(description='Resolve a name using DNS')
parser.add_argument('name', help='name that you want to look up in DNS')
lookup(parser.parse_args().name)
You can see that only one type of DNS query can be attempted at a time, so this small script runs in a loop asking
for different types of records pertaining to the single hostname that has been given as its command-line argument.
Running this against python.org will immediately teach you several things about DNS.
$ python dns_basic.py python.org
python.org. 42945 IN A 140.211.10.69
python.org. 86140 IN MX 50 mail.python.org.
python.org. 86146 IN NS ns4.p11.dynect.net.
python.org. 86146 IN NS ns3.p11.dynect.net.
python.org. 86146 IN NS ns1.p11.dynect.net.
python.org. 86146 IN NS ns2.p11.dynect.net.
As you can see from the program, each “answer” in the reply that has been returned is represented by a sequence
of objects. In order, the keys that get printed on each line are as follows:
• The name looked up.
• The time in seconds that you are allowed to cache the name before it expires.
• The “class” like IN, which indicates that you are being returned Internet address responses.