../_images/th-dns.png

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.

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