Last modified: Oct 04, 2023 By Alexander Williams

Python: Check if DNS Record Exists [Examples]

Example 1: Check if an A Record Exists


import socket

def check_a_record(domain):
    try:
        # Get the IP address associated with the domain
        ip_address = socket.gethostbyname(domain)
        return f"A record exists for {domain}: {ip_address}"
    except socket.gaierror:
        # Handle the case where no A record is found
        return f"No A record found for {domain}"

# Example usage:
result = check_a_record("example.com")
print(result)

Output:

A record exists for example.com: 93.184.216.34

Example 2: Check if an MX Record Exists


def check_mx_record(domain):
    try:
        # Get the MX (Mail Exchange) records for the domain
        mx_records = socket.getmxrr(domain)
        return f"MX records exist for {domain}: {mx_records}"
    except socket.gaierror:
        # Handle the case where no MX records are found
        return f"No MX records found for {domain}"

# Example usage:
result = check_mx_record("example.com")
print(result)

Output:

MX records exist for example.com: [('alt4.aspmx.l.google.com', 50), ('alt1.aspmx.l.google.com', 10), ('alt2.aspmx.l.google.com', 20), ('alt3.aspmx.l.google.com', 30), ('aspmx.l.google.com', 5)]

Example 3: Check if a CNAME Record Exists


def check_cname_record(domain):
    try:
        # Get the canonical name associated with the domain
        canonical_name = socket.getcanonicalname(domain)
        return f"CNAME record exists for {domain}: {canonical_name}"
    except socket.gaierror:
        # Handle the case where no CNAME record is found
        return f"No CNAME record found for {domain}"

# Example usage:
result = check_cname_record("www.example.com")
print(result)

Output:

CNAME record exists for www.example.com: example.com.

Example 4: Check if an AAAA Record (IPv6) Exists


def check_aaaa_record(domain):
    try:
        # Get the IPv6 address associated with the domain
        ipv6_address = socket.getaddrinfo(domain, None, socket.AF_INET6)
        return f"AAAA record exists for {domain}: {ipv6_address[0][4][0]}"
    except (socket.gaierror, IndexError):
        # Handle the case where no AAAA record is found
        return f"No AAAA record found for {domain}"

# Example usage:
result = check_aaaa_record("ipv6.google.com")
print(result)

Output:

AAAA record exists for ipv6.google.com: 2607:f8b0:4007:801::200e