DNS Lookup using Python

Python, Scripts, Websites - November 28, 2022 - 3 min read

Overview

What is DNS?

The Domain Name System (DNS) is essentially the Internet's phonebook. Web browsers communicate using Internet Protocol (IP) addresses. DNS converts domain names to IP addresses so that browsers can access Internet resources. DNS servers remove the need for humans to remember IP addresses.

DNS Record Types

  1. A Record - It is the most basic type of DNS record. Here A stands for address. It displays the domain's IP address.
  2. AAAA Record - This is an IP address record that is used to determine the IP address of the computer that is connected to the domain. It is conceptually similar to A records, but it only specifies the server's IPv6 address rather than IPv4.
  3. PTR Record - PTR is an abbreviation for pointer record, which is used to translate IP addresses to domain names or hostnames. It is used to perform a DNS lookup in reverse.
  4. NS Record - The nameserver (NS) record specifies which server is authoritative for the given domain, i.e. which server contains the actual DNS records. A domain can have multiple NS records, including the primary and backup name servers.
  5. MX Record - MX is an abbreviation for Mail Exchanger record, which is a resource record that specifies the mail server that accepts emails on behalf of the domain. If multiple mail servers are present for load balancing and redundancy, it has preference values based on mail prioritisation.
  6. SOA Record - SOA records, which stand for Start of Authority records, are a type of resource record that contains information about zone administration, particularly zone transfers defined by the zone administrator.
  7. CNAME Record - Canonical Name record (CNAME) is used in mapping the domain name as an alias for another domain. It always points to another domain and never to an IP address.
  8. TXT Record - These records contain text information from sources that are not in the domain. TXT records can be used for a variety of purposes, including domain ownership verification and email security.
  9. SRV Record - A port for specific services is specified.

Python program for extracting dns information

Prepare your tools

We'll be using the dnspython module in Python. You can install this module using the pip command like this:

pip install dnspython

Python Code

from dns.resolver import resolve
from dns.rdatatype import RdataType
from dns.exception import DNSException

def extract(domain):
    data = {}

    for query_type in RdataType:
        try:
            dnsData = resolve(domain, query_type)
            data[query_type.name] = [i.to_text() for i in dnsData]
        except DNSException:
            continue

    return data

if __name__ == "__main__":
    domain = input("Enter Domain Name: ")
    data = extract(domain)

    for k, v in data.items():
        print(k.ljust(8)," : ",v)

Output Screenshot

Tool Preview

Use our tool