DNS from Perl


Perl has gethostby* functions available in libc, and these are the ones most people use. The use of the gethostby* functions is documented in the perlipc man page. Because DNS lookups are (or can be) slow, the results are prime suspects for caching in a hash. The following code fragment looks up the IP address of the host named by the $host variable:

 use Socket; ... # Check cache first if (exists($address{$host})) { # We know the address already $thataddr=$address{$host}; } else { # Cache miss, get and remember. (my $fqdn, undef, undef, undef, $thataddr) = gethostbyname($host); # Hostname lookup failure?  Cache the miss. if (defined($fqdn)) { $address{$host}=$thataddr; $address{$fqdn}=$thataddr if $fqdn ne $host; } else { $thataddr=$address{$host}=undef; } } if ($thataddr) { print "$host resolves to ",inet_ntoa($thataddr),"\n"; } else { print "$host does not resolve\n"; } 

This code caches answers, but the caching code does not take the TTL into account. It is not available from the API, but if the program is "alive" for a relatively short time (for hours or less), it is reasonable to ignore the TTL and use the same address throughout the lifetime of the program .

The Net::DNS Module

The module Net::DNS, written by Mike Fuhr, is available on CPAN. It provides a more complete DNS interface, including DNS UPDATE. If you are unfamiliar with CPAN, see the system Perl man pages or http://www.cpan.org/ . The Net::DNS home page is at http://www.fuhr.org/~mfuhr/perldns/ .

The Net::DNS module enables you to build DNS query packets by calling object methods and then sending and later analyzing the answer. The interfaces are high-level and very powerful, and the documentation is good and filled with examples. This code example is from the man page; it looks up the available records of http://foo.bar.com and prints any A records returned:

 use Net::DNS; $res = new Net::DNS::Resolver; $query = $res->search("http://foo.bar.com"); if ($query) { foreach $rr ($query->answer) { next unless $rr->type eq "A"; print $rr->address, "\n"; } } else { print "query failed: ", $res->errorstring, "\n"; } 

This module does not use the OS resolver at all. It uses DNS directly and parses your /etc/resolv.conf to obtain the address of your nameservers. Using this library, you also can issue non-blocking, asynchronous DNS queries. See my mresolv2 script for an example (it can be found on the perldns home page).



The Concise Guide to DNS and BIND
The Concise Guide to DNS and BIND
ISBN: 0789722739
EAN: 2147483647
Year: 1999
Pages: 183

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net