DNS Lookup With Python

DNS Lookup With Python

ยท

5 min read

Hello techie๐Ÿ‘‹, welcome to my little world again. Today, we shall learn how to perform DNS lookups using only python.

DNS lookups utilize DNS records to translate IP addresses and domain names or email addresses.

DNS clients and DNS servers both use caching to speed up the domain name lookup process and to ease traffic on the root servers.

๐Ÿ”ธ Hold On, What is DNS?

The Domain Name System (DNS) is basically the phonebook of the Internet. Humans access information online through domain names, like hashnode.com or octachart.com.

Web browsers interact through Internet Protocol (IP) addresses. DNS translates domain names to IP addresses so browsers can load Internet resources.

Each device connected to the Internet has a unique IP address that other machines use to find the device.

DNS servers eliminate the need for humans to memorize IP addresses such as 192.168.1.1 (in IPv4), or more complex newer alphanumeric IP addresses such as 2400:cb00:2048:1::c629:d7a2(in IPv6).

The IP addresses when translated to human-readable formats or words become known as domain names. The translation of domain names to IP addresses is managed by the python module dnspython.

This module also provides methods to find out CNAME and MX records.

๐Ÿ”ธ Windows nslookup

To find this information on your Windows machine.

๐Ÿ’จ run nslookup
๐Ÿ’จ run ipconfig /displaydns

You can type help for more inquiries but for example if I typed type=any hashnode.com in the nslookup shell; The following will be the output;

image.png

๐Ÿ”ธOnline Tools

Most of these online tools fetch DNS records for a domain and reports them in a priority list.

๐Ÿ›  MxToolbox : Visit ๐Ÿš€
๐Ÿ›  DNS Checker : Visit ๐Ÿš€
๐Ÿ›  WhatIsMyIPยฎ : Visit ๐Ÿš€
๐Ÿ›  DNS Lookup : Visit ๐Ÿš€

๐Ÿ”ธ Using Python Socket

You can use the socket module to return host IP addresses. Consider the example code below with explanation in the docstring;

def get_ips_by_dns_lookup(target, port=None):
    '''
        this function takes the passed target and optional port and does a dns
        lookup. it returns the ips that it finds to the caller.

        :param target:  the URI that you'd like to get the ip address(es) for
        :type target:   string
        :param port:    which port do you want to do the lookup against?
        :type port:     integer
        :returns ips:   all of the discovered ips for the target
        :rtype ips:     list of strings

    '''

    if not port:
        port = 443

    return list(map(lambda x: x[4][0], socket.getaddrinfo('{}.'.format(target),port,type=socket.SOCK_STREAM)))

ips = get_ips_by_dns_lookup(target='twitter.com')
print(ips)

The above will return:

image.png

You can alternatively run this simple script;

import socket

addr1 = socket.gethostbyname('google.com')
addr2 = socket.gethostbyname('yahoo.com')

print(addr1, addr2)

As you can see, we are limited with what we can do with sockets.

๐Ÿ”ธ Dnspython

Dnspython is a DNS toolkit for Python. It can be used for queries, zone transfers, dynamic updates, nameserver testing, and many other things.

Dnspython provides both high and low-level access to the DNS. The high-level classes perform queries for data of a given name, type, and class, and return an answer set.

๐Ÿ”ธ DNS Records

A DNS record is a database record used to map a URL to an IP address. DNS records are stored in DNS servers and work to help users connect their websites to the outside world.

You can pip install dnspython

If you have challenges with importing, installing or using it, read
๐Ÿ›  Stack Overflow Answers
๐Ÿ›  Official Read-The-Docs Installation

๐Ÿ”ธ Common DNS Records

๐Ÿ”น A record - The record that holds the IP (IPv4) address of a domain.
๐Ÿ”น AAAA - The record that contains the IPv6 address for a domain.
๐Ÿ”น CNAME record - Forwards one domain or subdomain to another domain, does NOT provide an IP address.
๐Ÿ”น MX record - Directs mail to an email server.
๐Ÿ”น TXT record - Lets an admin store text notes in the record. These records are often used for email security.
๐Ÿ”น NS record - Stores the name server for a DNS entry.
๐Ÿ”น SOA record - Stores admin information about a domain.
๐Ÿ”น SRV record - Specifies a port for specific services.
๐Ÿ”น PTR record - Provides a domain name in reverse-lookups.

Learn more from Cloudflare

In this particular article, I will focus mainly on A, CNAME & MX records.

๐Ÿ”น Finding A Records

In the below code we find the IP address for the domain using the resolve() method. Usually this mapping between IP address and domain name is also known as 'A' record.

import dns
import dns.resolver

result = dns.resolver.resolve('hashnode.com', 'A')
A_records = []

for IPval in result:
    A_records.append(IPval.to_text())
print(A_records)

When we run the above code, we get the following output:

['104.22.24.116', '172.67.10.98', '104.22.25.116']

๐Ÿ”น Finding CNAME Values

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 resolve() method below we specify the CNAME parameter to get the CNAME value.

result = dns.resolver.resolve('mail.hashnode.com', 'CNAME')

for cnameval in result:
    print('CNAME Target Address:', cnameval.target)

When we run the above code, we get the following output

CNAME Target Address: ghs.googlehosted.com.

๐Ÿ”น Finding MX Records

An MX record also called a 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 prioritize mail delivery if multiple mail servers are available.

Similar to the above scripts we can find the value for the MX record using the MX parameter in the resolve() method.

result = dns.resolver.resolve('hashnode.com', 'MX')

for exdata in result:
    print('MX Record: ',exdata)

When we run the above code, we get the following output โˆ’

MX Record:  10 aspmx.l.google.com.
MX Record:  20 alt1.aspmx.l.google.com.
MX Record:  30 alt2.aspmx.l.google.com.
MX Record:  40 aspmx2.googlemail.com.
MX Record:  50 aspmx3.googlemail.com.

๐Ÿ“Œ GitHub Repo

๐Ÿ”ธNotes & Resources ๐Ÿ“‘

๐Ÿ“Œ DNSpython Docs- Read The Docs
๐Ÿ“Œ Python for network penetration - Infosec Institute
๐Ÿ“Œ DNS Enumeration - Security Trails
๐Ÿ“Œ 10 most used Nslookup commands - CloudNS

๐Ÿ”ธ Conclusion โœŒ

Some websites are protected and you may not hit them directly using the IP address.

This article is for educational purposes and I am not responsible for any intended personal use case.

That's it!

If you enjoyed this article, consider subscribing to my channel for related content especially about Tech, Python & Programming.

๐Ÿ“ขFollow me on Twitter:โ™ฅ โ™ฅ

Ronnie Atuhaire

ย