5.1. Programming and DNS

Domain Name System (DNS)

DNS is a system of hierarchical, distributed, cached databases used with the TCP/IP Internet to determine and IP address from a given host name and also provide the reverse look-up. Authoritative servers provide this information for each domain and sub-domain.

You may be familiar with how to use nslookup or host commands to translate between host name and IP addresses. In DNS tables, the listings of IP address for specific machine names are call A records.

C:\Documents and Settings\tim>nslookup www.ksu.edu
Server:  ns.sal.ksu.edu

Non-authoritative answer:
Name:    www.ksu.edu

We can also use DNS to find a list of servers to use for sending an e-mail message to someone at a particular domain name. These are called MX records.

C:\Documents and Settings\tim>nslookup
Default Server:  ns.sal.ksu.edu

> set q=mx
> ksu.edu
Server:  ns.sal.ksu.edu

Non-authoritative answer:
ksu.edu MX preference = 10, mail exchanger = meritmail-mx2.merit.edu
ksu.edu MX preference = 10, mail exchanger = meritmail-mx1.merit.edu

ksu.edu nameserver = ns-2.ksu.edu
ksu.edu nameserver = nic.kanren.net
ksu.edu nameserver = ns-1.ksu.edu
ksu.edu nameserver = kic.kanren.net
ns-1.ksu.edu    internet address =
ns-2.ksu.edu    internet address =

In most cases, it is not required that you write code that interacts directly with the DNS system. From the socket module, the socket.gethostbyname(), socket.gethostbyaddr() socket.getaddrinfo() and socket.connect() functions do the DNS resolution for us. Even when sending e-mail messages, we generally only need find our SMTP server. It finds the MX records of the destination domain and connects to the appropriate server to send the message. None the less, DNS is a very important part of networking. So for those occasions when our program needs to do DNS look-ups or reverse look-ups, it is a simple matter with Python.

The two most common Python DNS modules are pyDNS and dnspython. I chose to use the later for the small programming DNS assignment because it is a little simpler to use and seems to be in more common use. (See Programming Assignment 2 – DNS MX Record Lookups)

Dnspython provides both high and low level access to DNS. The high level classes perform queries for data of a given name, type, and class; and returns an answer set. The low level classes allow direct manipulation of DNS zones, messages, names, and records. [DNSPYTHON] See: Dnspython home page

5.1.1. Example dnspython Usage

The following example retrieves the e-mail servers (MX records) and preferences for a domain:

import dns.resolver

answers = dns.resolver.query('gmail.com', 'MX')
for rdata in answers:
    print 'Host', rdata.exchange, 'has preference', rdata.preference

Table Of Contents

Previous topic

5. Topic 2 – Programs using DNS

Next topic

5.2. Programming Assignment 2 – DNS MX Record Lookups

This Page