6. DNS Protocol

6.1. dnspython

6.1.1. Installation

$ pip install dnspython

6.1.2. Basic DNS queries

import dns.resolver

name = 'python.astrotech.io'

answer = dns.resolver.query(name, 'MX')
import dns.resolver

name = 'python.astrotech.io'
answer = dns.resolver.query(name, 'MX')

# readthedocs.io.

# 1541631181.7326112

# [<DNS python.astrotech.io. IN CNAME RRset>, <DNS readthedocs.io. IN MX RRset>]

# readthedocs.io. 71 IN MX 10 aspmx3.googlemail.com.
# readthedocs.io. 71 IN MX 10 aspmx2.googlemail.com.
# readthedocs.io. 71 IN MX 5 alt1.aspmx.l.google.com.
# readthedocs.io. 71 IN MX 1 aspmx.l.google.com.
# readthedocs.io. 71 IN MX 5 alt2.aspmx.l.google.com.

# [
#   <DNS IN MX rdata: 10 aspmx3.googlemail.com.>,
#   <DNS IN MX rdata: 10 aspmx2.googlemail.com.>,
#   <DNS IN MX rdata: 5 alt1.aspmx.l.google.com.>,
#   <DNS IN MX rdata: 1 aspmx.l.google.com.>,
#   <DNS IN MX rdata: 5 alt2.aspmx.l.google.com.>
# ]
import dns.resolver

name = 'python.astrotech.io'
records = ['A', 'AAAA', 'MX', 'NS', 'TXT', 'SOA']

for record in records:
    answer = dns.resolver.query(name, record, raise_on_no_answer=False)

    if answer.rrset is not None:

6.1.3. Zone transfer

  • DNS Zone transfer is the process where a DNS server passes a copy of part of it’s database (which is called a “zone”) to another DNS server.

  • DNS zone transfer, also sometimes known by the inducing DNS query type AXFR, is a type of DNS transaction.

  • It is one of the many mechanisms available for administrators to replicate DNS databases across a set of DNS servers.

import dns.query
import dns.zone

z = dns.zone.from_xfr(dns.query.xfr('nsztm1.digi.ninja', 'zonetransfer.me'))
names = z.nodes.keys()

for n in names:
    print z[n].to_text(n)

6.1.4. Reverse DNS lookup (PTR record)

  • Reverse DNS resolution (rDNS) is the determination of a domain name associated with an IP address via querying DNS (the reverse of the usual “forward” DNS lookup of an IP from a domain name.)

  • To do a reverse lookup of the IP address the PTR record for the domain name would be looked up, and found to point to google-public-dns-b.google.com.

from dns import reversename

domain_address = reversename.from_address('')


ip_address = reversename.to_address(domain_address)

from dns import resolver

domain_name = str(resolver.query(domain_address,"PTR")[0])

# google-public-dns-b.google.com.