Resolve IP Addresses to DNS Names
Submitted by johnk on Sun, 05/11/2008 - 11:19.
Sometimes, you have textual data, like log files, with IP addresses. You sometimes want this data to show hostnames instead.
This script converts IP addresses in the standard input to hostnames. (Script is based on one I found in perlmonks.org.)
#!/usr/bin/perl -w
#
# Resolve IP addresses in web logs.
# Diego Zamboni, Feb 7, 2000
# John Kawakami, May 12, 2008
use Socket;
# Local domain mame
$localdomain = 'slaptech.net';
while (my $l = <>) {
if ($l =~ /^(.*?)(\d+\.\d+\.\d+\.\d+)(.*?)$/) {
$pre = $1;
$address = $2;
$post = $3;
if ($cache{$address}) {
$addr = $cache{$address};
}
else {
$addr=inet_aton($address);
if ($addr) {
$name=gethostbyaddr($addr, AF_INET);
if ($name) {
# NOTE: To ensure the veracity of $name, we really
# would need to do a gethostbyname on it and compare
# the result with the original $f[0], to prevent
# someone spoofing us with false DNS information.
# See the comments below. For this application,
# we don't care too much, so we don't do this.
# Fix local names
if ($name !~ /\./) {
$name.=$localdomain;
}
$cache{$address}=$name;
$addr=$name;
}
else
{
$addr = $address;
}
}
else
{
$addr = $address;
}
}
# print $pre.'-'.$addr.'-'.$post."\n";
print $pre.$addr.$post."\n";
}
else {
print $_;
}
}
To use it, save the code into the file "resolve", do a "chmod u+x resolve" on it, and then try the following:
last -10 | ./resolve
