9.8.1 Problem
You want to look up resource records within a computer program.
9.8.2 Solution
One of the easiest ways to look up records programmatically is to use the Net::DNS Perl module, originally developed by Michael Fuhr and now maintained by Chris Reinhardt. You can get a copy of Net::DNS from http://www.net-dns.org/, or from CPAN.
Once you've installed Net::DNS, using it is easy. A program to look up a domain name's addresses could be as simple as this:
#!/usr/bin/perl -w use Net::DNS; # If the user didn't specify a domain name to look up, exit die "Usage: $0 " unless (@ARGV == 1); # Create a resolver object my $res = Net::DNS::Resolver->new; # Look up A records (the default) for the domain name argument my $query = $res->search($ARGV[0]); # If this returned an answer... if ($query) { # Print every A record in the answer message foreach my $rr ($query->answer) { next unless $rr->type eq "A"; print $rr->address, " "; } # Otherwise print an error } else { print "query failed: ", $res->errorstring, " "; }
Looking up other types of records only requires adding the type after the domain name argument; for example, changing the line of the script that calls $res->search to:
my $query = $res->search($ARGV[0], "MX");
And, naturally, you'd need to change the type of record you looked for in the foreach loop and what you printed when you found a record of the right type:
# Print every MX record in the answer message foreach my $rr ($query->answer) { next unless $rr->type eq "MX"; print $rr->string, " ";
9.8.3 Discussion
There are lots of ways to look up records -- both in Perl and in other programming languages. Choose whichever language you're most comfortable with: It's a good bet that it supports some method of querying name servers. For the fastest performance possible, you should probably use C. Chapter 15 of DNS and BIND describes how to use C's resolver routines to do simple DNS lookups.
9.8.4 See Also
The Net::DNS web site at http://www.net-dns.org/, and Chapter 15 of DNS and BIND.
Getting Started
Zone Data
BIND Name Server Configuration
Electronic Mail
BIND Name Server Operations
Delegation and Registration
Security
Interoperability and Upgrading
Resolvers and Programming
Logging and Troubleshooting
IPv6