Querying DNS for CNAMEs for a server

You didn’t specify what your environment is but if you’re using Unix I think a combination of dig and grep should work. ns.example.com should be the hostname of your nameserver, example.com is the domain your host is part of, and HOST is the host that you want to find all the CNAME records for. That’s actually a tab character in the grep command, not literally <TAB> (you may have to adjust the grep string).

Also your nameserver needs to to be configured to allow zone transfers, the particulars of which will be implementation dependent.

dig @ns.example.com example.com axfr |grep 'CNAME<tab>HOST$'

Or if you’re on Windows you could use nslookup:

C:\> nslookup
> name ns.example.com
> ls -a example.com FILE

This should output all of the records for the domain example.com that ns.example.com “knows about” to FILE. You can then use whatever tool you want to sort through the text file looking for the corresponding CNAMES.

Or with this untested (but seemly correct looking) perl script:

#!/usr/bin/perl

use Net::DNS;

($target, $zone) = @ARGV;

$res = new Net::DNS::Resolver;
foreach $rr ($res->axfr($zone)) {
     print $rr->name."\n" if (($rr->type eq "CNAME") && ($rr->rdatastr eq $target."."));
}

A couple of points for completeness:

  • As @womble stated, there’s no equivalent of a PTR record for a CNAME. You’ll have to use some contextual awareness by sorting through all the zone information for CNAMES that correspond to the A records of your host.
  • This only works for your DNS server (and if you have permission to view zone information). There’s no way to “trace” CNAMES for your host that belong on other zones.
  • As @BillThor states, there are other ways to aliases a hostname beyond CNAMES. Again, you’ll need some contextual awareness.

Leave a Comment