Compare DNS record sets without querying a server
Normalize supplied A, AAAA and CNAME exports and report exact set differences.
Compare the record, not just its owner name
An owner can have multiple address records. Compare the tuple of normalized name, record type and value so a changed address is visible as one missing record and one unexpected record. Identical duplicates do not create extra changes under this set-based policy.
For this exercise, names are ASCII hostname labels. Strip surrounding whitespace, casefold and remove one trailing dot. Wildcards, underscore labels and internationalized-name conversion are outside this export grammar. CNAME targets follow the same rule. This is a deliberately limited comparison format, not a general DNS-zone parser.
Address values have types too
An A record must contain an IPv4 address; AAAA must contain IPv6. Parse the value with ipaddress and use its canonical spelling. Reject zone identifiers and incompatible families. Record type labels are case-insensitive and normalized to uppercase.
Ignore extra export fields such as TTL for this comparison. Their exclusion is a policy decision, not a claim that TTL is unimportant. A separate check could assess it when needed.
Validate every record before returning a result, then sort missing and unexpected sets by name, type and value. This function only compares supplied exports. It does not contact a resolver, follow CNAME chains or establish whether a name currently resolves on a live network.
from ipaddress import ip_address
name = " Portal.Example.Test. ".strip().casefold().removesuffix(".")
print(name, str(ip_address("2001:0DB8:0:0::1")))
Put it into practice.
Define compare_dns(expected, observed), returning {missing:[...], unexpected:[...]}. Normalize names by strip().casefold() and removal of one trailing dot; allow only ASCII hostname labels (1..63 chars, alphanumeric ends, internal hyphens), total <=253 chars. Normalize type to uppercase; support A/AAAA/CNAME only. A/AAAA values must be unscoped IP strings of the correct family and return canonical text. CNAME values use name normalization. Invalid records raise ValueError. Compare (name, type, value) sets, ignoring duplicates and extra fields such as TTL. Return sorted name, type, value rows and preserve inputs.
See an explained solution
from ipaddress import ip_address
import re
def dns_record(row):
def name(value):
if not isinstance(value,str):
raise ValueError("DNS name must be text")
value = value.strip().casefold().removesuffix(".")
labels = value.split(".")
if len(value) > 253 or any(not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",label) for label in labels):
raise ValueError("Invalid export hostname")
return value
owner, kind = name(row["name"]), row["type"].strip().upper()
if kind in ("A","AAAA"):
value = row["value"]
if not isinstance(value,str) or "%" in value:
raise ValueError("Invalid address value")
address = ip_address(value.strip())
if address.version != {"A":4,"AAAA":6}[kind]:
raise ValueError("Record family mismatch")
value = str(address)
elif kind == "CNAME":
value = name(row["value"])
else:
raise ValueError("Unsupported record type")
return {"name":owner,"type":kind,"value":value}
def compare_dns(expected, observed):
def records(rows):
return {tuple(dns_record(row)[key] for key in ("name","type","value")) for row in rows}
wanted, actual = records(expected), records(observed)
convert = lambda rows:[dict(zip(("name","type","value"),row)) for row in sorted(rows)]
return {"missing":convert(wanted-actual),"unexpected":convert(actual-wanted)}
if __name__ == "__main__":
print(compare_dns([{"name":"portal.example.test","type":"A","value":"192.0.2.10"}], []))
The comparison treats equivalent spelling and duplicate rows consistently while retaining changes to actual record values. No resolver behavior is inferred from a saved export.