Last active
September 14, 2020 00:09
-
-
Save mattpascoe/6ff7fee7984046587ba2b8dedfe4733d to your computer and use it in GitHub Desktop.
Simple perl script to do inline reverse DNS lookups of IPs. It processes stdin.. so just 'cat somefile | ./ip2name.pl'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
# TODO: make command line options possible use $endline as selector | |
###$endline=true; | |
# TODO: allow a comment character in the mode that prints at the end of a line. user passable comment character. | |
# TODO: make it work with ipv6.. for now its ipv4 only | |
use Socket; | |
my %dnscache; | |
my $commentchar = "#"; | |
$FILE = "-"; | |
open(FILE) or die("Could not open file."); | |
foreach $line (<FILE>) { | |
my $tmpline = $line; | |
my $namelist; | |
# Loop through the current line and find all IP addresses and process each one. | |
while ($tmpline =~ /((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))/o) { | |
my $value = $1; | |
## Test to see if we have already looked for this entry before | |
if (!$dnscache{$value}) { | |
$dnscache{$value} = ""; | |
## Do DNS lookup for the names | |
my $ipaddrs = gethostbyaddr(inet_aton($value), AF_INET); | |
if (!$ipaddrs) { $ipaddrs = "UNKNOWN_IP"; } | |
my $tmp = $ipaddrs; | |
#print "DEBUG => Found the following IP addresses for $value: $ipaddrs\n"; | |
## If a name was found, put it in dnscache hash | |
if ($tmp) { | |
$dnscache{$value} = $tmp; | |
} | |
} | |
# If the user wants an end of line list, build the list | |
if ($endline) { | |
$tmpline =~ s/$value//; | |
if (!$namelist) { | |
$namelist = $dnscache{$value} | |
} else { | |
$namelist = $namelist.", ".$dnscache{$value}; | |
} | |
} else { | |
# If the user wants in line replacement of names | |
# Remove the current IP from the temporary line so we can find the next IP | |
$tmpline =~ s/$value//g; | |
## Replace the IP with the DNS lookup results | |
$line =~ s/$value/$value \($dnscache{$value}\)/g; | |
} | |
} | |
# If there is a list of names, add it to the end of the line | |
if ($namelist) { $line =~ s/$/\t\t$commentchar ($namelist)/; } | |
# Print the line | |
print $line; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment