Python - DNS Look-up


Advertisements

The IP addresses when translated to human readable formats or words become known as domain names. The translation of domain names to IP address is managed by the python module dnspython.This module also provides methods to find out CNAME and MX records.

Finding 'A' Record

In the below program we find the ip address for the domain using the dns.resolver method. Usually this mapping between IP address and domain name is also known as 'A' record.

import dnspython as dns
import dns.resolver

result = dns.resolver.query('tutorialspoint.com', 'A')
for ipval in result:
    print('IP', ipval.to_text())

When we run the above program, we get the following output −


('IP', u'94.130.81.180')

Finding CNAME Value

A CNAME record also known as Canonical Name Record is a type of record in the Domain Name System (DNS) used to map a domain name as an alias for another domain. CNAME records always point to another domain name and never directly to an IP address. In the query method below we specify the CNAME parameter to get the CNAME value.

import dnspython as dns
import dns.resolver
result = dns.resolver.query('mail.google.com', 'CNAME')
for cnameval in result:
    print ' cname target address:', cnameval.target

When we run the above program, we get the following output −

cname target address: googlemail.l.google.com.

Finding MX Record

A MX record also called mail exchanger record is a resource record in the Domain Name System that specifies a mail server responsible for accepting email messages on behalf of a recipient's domain. It also sets the preference value used to prioritizing mail delivery if multiple mail servers are available. Similar to above programs we can find the value for MX record using the 'MX' parameter in the query method.

result = dns.resolver.query('mail.google.com', 'MX')
for exdata in result:
    print ' MX Record:', exdata.exchange.text()

When we run the above program, we get the following output −

MX Record:	ASPMX.L.GOOGLE.COM.
MX Record:	ALT1.ASPMX.L.GOOGLE.COM.
MX Record:	ALT2.ASPMX.L.GOOGLE.COM.

The above is a sample output and not the exact one.

Advertisements