A and CNAME records & loop detection

Follow DNS records

Lesson 13 of 20 · 11 min · Module 4: Names and the web

DNS turns names into addresses. Some names are aliases: a CNAME record says "look up this other name instead".

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Distinguish A and CNAME records
  • Follow a chain with a loop
  • Protect a loop against cycles

The idea

An A record holds an IPv4 address. A CNAME points to another name, which may itself be a CNAME. A resolver follows the chain until it reaches an A record, and it must stop if the chain loops.

records = {"www.example.test": ("CNAME", "example.test"), "example.test": ("A", "203.0.113.10")}
print(records["www.example.test"])

01Aliases are common

www.example.com is often a CNAME to example.com, and content networks add more hops. Following the chain is routine work for every resolver.

02Unpack each record

kind, value = records[name] splits the pair. An A record ends the search; a CNAME replaces name with its target and the loop continues.

kind, value = ("CNAME", "shop.test")
print(kind, value)
Output
CNAME shop.test

03Remember where you have been

A misconfiguration such as a → b → a would make a naive loop run forever. A set of visited names detects the cycle on the first repeat.

Your turn

Write resolve(name, records). records maps a name to ("A", address) or ("CNAME", target). Follow CNAMEs and return the final address. Raise LookupError if a name is missing or if the chain visits the same name twice.

What the checks look for

  • Returns an A record directly
  • Follows a chain of CNAMEs
  • Raises LookupError for a missing name
  • Raises LookupError for a CNAME loop
Try it in the editor →

Take this with you

Follow CNAMEs to an A record, and track visited names so a loop cannot trap you.

Go a little further

Return the whole chain of names along with the final address, which is useful when debugging DNS.

Learn Networking Foundations for free

20 short lessons with real code and instant checks.

See the whole course →