I l@ve RuBoard Previous Section Next Section

9.8 Looking Up Records Programmatically

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 <domain name>" 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, "\n";
    }

# Otherwise print an error
} else {
    print "query failed: ", $res->errorstring, "\n";
}

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, "\n";

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.

    I l@ve RuBoard Previous Section Next Section