I'd recommend using strict
and warnings
in all Perl scripts.
Ask for mail exchanger records with nslookup -q=MX
to make the script stable. The output of nslookup -q=any
might include the MX record but not always (I suppose it returns any record type it finds, not necessarily MX?).
Edit: This script works for me:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %lookup_cache = ();
sub valid_address {
my($addr) = @_;
my($domain, $valid);
# Lower-case address
$addr = lc($addr);
# Validate format of address
return(0) unless ($addr =~ /^[^@]+@([-\w]+\.)+[a-z]{2,4}$/);
# Grab domain
$domain = (split(/@/, $addr))[1];
# Lookup and return cached result if it exists
my $cached_result = $lookup_cache{$domain};
if (defined $cached_result)
{
return $cached_result;
}
# Do domain lookup
$valid = 0;
if (open(DNS, "nslookup -q=MX $domain |"))
{
while (<DNS>) {
$valid = 1 if (/^$domain.*\s(mail exchanger|internet address)\s=/i);
}
}
# Store cached result for later
$lookup_cache{$domain} = $valid;
return $valid;
}
while (<>) {
my $addy = $_;
$addy =~ s/\s+$//;
if ($addy)
{
print "$addy " . (valid_address($addy) ? 'valid' : 'invalid') . "\n";
}
}