Python Network Programming DNS Query

Python Network Programming DNS Query

An IP address translated into human-readable form or text is called a domain name. The translation of domain names to IP addresses is managed by the Python module dnspython. This module also provides methods for looking up CNAME and MX records.

Looking Up ‘A’ Records

In the following program, we use the dns.resolver method to find the IP address for a domain name. This mapping between IP addresses and domain names is often referred to as an ‘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 −

<br>('IP', u'94.130.81.180')

Finding CNAME Values

A CNAME record, also known as a classic name record, is a type of record in the Domain Name System (DNS) that maps one domain name to an alias for another. A CNAME record always points to another domain name, not directly to an IP address. In the query method below, we specify the CNAME parameter to obtain 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 Records

An MX record, also known as a mail exchanger record, is a resource record in the Domain Name System that specifies a mail server responsible for accepting email on behalf of the recipient’s domain name. If multiple mail servers are available, it also sets a preference value for sending email first. Similar to the above program, we can find the value of the 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, not the exact output.

Leave a Reply

Your email address will not be published. Required fields are marked *