Perl Net::DNS / Querying DNS Servers
Posted: Mon, Apr 18 10:33 AM (PDT)Perl Net::DNS library can be used to write powerful web or OS system applications involving DNS lookups and queries. In this tutorial I will show you how to write a DNS diagnostic application involving DNS and resolver.
Installing Net::DNS
If you have a Linux or Unix server, you can install Net::DNS library using cpan. You must have perl already installed.
cpan -i Net::DNS
Checking parent nameservers
Query parent nameservers from root level to see if the nameservers are listed.
#!/usr/bin/perl
my $domain = "atlas365.com";
use Net::DNS::Resolver::Recurse;
my $dns = Net::DNS::Resolver::Recurse->new;
$dns->tcp_timeout(2);
$dns->udp_timeout(2);
$dns->debug(0);
my @root_ns = map $_ . '.root-servers.net', 'a'..'m';
$dns->hints(@root_ns);
my $answer = $dns->query_dorecursion($domain, "NS");
print "Parent nameservers:\n";
foreach my $p_ns ($answer->additional) {
print $p_ns->name."(".$p_ns->rdatastr.")\n";
}
This example will output the nameserver NS records that are listed at parent level.
Check domain IP address (A record)
The A record in DNS domain zone maps a domain or sub.domain to it’s corresponding IP address.
#!/usr/bin/perl
my $domain = "www.atlas365.com";
use Net::DNS::Resolver;
my $dns = Net::DNS::Resolver->new;
my $query = $dns->search($domain);
if ($query) {
foreach my $rr ($query->answer) {
next unless $rr->type eq "A";
print $rr->address."\n";
}
} else { print "Unable to obtain A record for $domain\n"; }
Check domain MX records
Simple code to detect MX records of domain
#!/usr/bin/perl
my $domain = "atlas365.com";
use Net::DNS;
my $dns = Net::DNS::Resolver->new;
my @mx = mx($dns, $domain);
if (@mx) {
foreach my $rr (@mx) {
print $rr->preference.":".$rr->exchange."\n";
}
} else { print "Unable to obtain MX records for $domain\n"; }
Check domain SPF record
SPF is widely used in domain DNS text record for preventing spam. For more information see http://www.openspf.org
This is an example how to detect SPF record by querying the DNS server.
#!/usr/bin/perl
my $domain = "atlas365.com";
use Net::DNS::Resolver;
my $dns = Net::DNS::Resolver->new;
my $query = $dns->search($domain, "TXT");
if ($query) {
foreach my $rr ($query->answer) {
my $spf = lc($rr->txtdata);
if ($spf=~/v\=spf/) {
print "SPF record: $spf\n";
}
}
}
Tags:
