# Set output format
if ($format eq "csv") {
$lineEnd = "\n";
}
elsif ($format eq "csvEx") {
$lineEnd = "\%EOL\%"
}
else {
print "Unknown format '$format'\n";
exit(1);
}
# Although Socket could be used instead of regex and manual validation, the behaviour and availability is not platform consistent.
sub _is_ipv4 {
shift if ref $_[0];
my $value = shift;
return undef unless defined($value);
# Capture each octet using a regex, so we can examine their range
my (@octets) = $value =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
return undef unless (@octets == 4);
foreach (@octets) {
# False if octet is outside range 0-255 or has a leading 0s (e.g 010 )
return undef if $_ < 0 || $_ > 255;
return undef if $_ =~ /^0\d{1,2}$/;
}
return join('.', @octets);
}
# Process queries based on query type (A or PTR)
foreach my $query (@queries) {
if (_is_ipv4($query)) {
# PTR Record lookup
my $hostname = gethostbyaddr(inet_aton($query), AF_INET);
if ($hostname){
print "$query,$hostname$lineEnd";
}
}
else {
# A Record lookup, returning first address only
my @result = gethostbyname($query);
if (@result) {
my $ipaddr = inet_ntoa($result[4]);
print "$ipaddr,$query$lineEnd";
}
}
}