Reply to comment

Resolve IP Addresses to DNS Names

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

Reply

The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.

More information about formatting options

3 + 14 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.