Good morning, I appreciate any assistance that I can get from the monks out there. I am able to get this to work for me so that I can do a hostname lookup if I only specify one hostname in the script. What I want to do is have a file with hostnames and do lookups for each name in the file. Here is the code that works, and the output:
#!/usr/bin/perl
use strict;
use warnings;
use Net::DNS::Resolver;
my $hostname = 'perlmonks.org';
my $res = Net::DNS::Resolver->new(
nameservers => [qw(8.8.8.8)],
);
my $query = $res->search($hostname);
if ($query) {
foreach my $rr ($query->answer) {
next unless $rr->type eq "A";
print "Found an A record for $hostname: ".$rr->address;
print "\n";
}
}
This is the output you get when you run it:
Found an A record for perlmonks.org: 66.39.54.27
Found an A record for perlmonks.org: 216.92.34.251
Found an A record for perlmonks.org: 209.197.123.153
So now taking it a step further, I want to check a whole file of names. This is the code I have, but it's not working. Can someone please help and let me know where I went wrong?
#!/usr/bin/perl
use strict;
use warnings;
use Net::DNS::Resolver;
open FILE, "<hostname_check.txt" || die $!;
while (<FILE>) {
my $res = Net::DNS::Resolver->new(
nameservers => [qw(8.8.8.8)],
);
my $query = $res->search($_);
if ($query) {
foreach my $rr ($query->answer) {
next unless $rr->type eq "A";
print "Found an A record for $_: ".$rr->address;
print "\n";
}
}
}
close FILE;
---------- Post updated at 08:25 AM ---------- Previous update was at 08:01 AM ----------
I found the mistake.
Here is the updated code that works:
#!/usr/bin/perl
use strict;
use warnings;
use Net::DNS::Resolver;
my $res = Net::DNS::Resolver->new(
nameservers => [qw(8.8.8.8)],
);
open FILE, "<hostname_check.txt" || die $!;
while (<FILE>) {
chomp;
my $hostname = $_;
my $query = $res->search($hostname);
if ($query) {
foreach my $rr ($query->answer) {
next unless $rr->type eq "A";
print "Found an A record for $_: ".$rr->address;
print "\n";
}
}
}
close FILE;
Here is the sample output: