#!/usr/bin/perl
#
# nsl.pl -
#    written by Charles Brabec
# 
# This program is free. Enjoy.

use Socket;

$in = shift;

# convert any hex encoded stuff
$in =~ s/%([a-f0-9]{2})/pack("C",hex($1))/eig;

# convert any oct encoded stuff
$in =~ s/\b(0\d+)\b/oct($1)/eig;

# strip ip from email address
$in =~ s/^.*\@//;

# strip domain from URL
$in =~ s#[hf]t+p://([^/]*)/?.*$#$1#;

# strip any remaining path stuff
$in =~ s#/.*$##;

# convert long-integer IP to dotted-quad
if ($in =~ /^\d+$/) { # integer host
   print "$in => ";

   # this is a long way to do it, but it handles overflows 
   # better than an unpack(pack()) method
   $in = oct($in) if ($in =~ /^0/);
   my $ll = $in; my $tt; $in = '';
   $tt = int($ll/256); $in = ($ll-$tt*256) . ".$in"; $ll = $tt;
   $tt = int($ll/256); $in = ($ll-$tt*256) . ".$in"; $ll = $tt;
   $tt = int($ll/256); $in = ($ll-$tt*256) . ".$in"; $ll = $tt;
   $tt = int($ll/256); $in = ($ll-$tt*256) . ".$in"; $ll = $tt;
   $in =~ s/\.$//;

   print "$in\n";
}

if ($in =~ /^[\d\.]+$/) {
   # got an IP address, lookup name
   print "$in => ", namelookup($in), "\n";
} else {
   # got a name, lookup number
   $out = nslookup($in);
   print "$in => $out\n";
   print "$out => ", namelookup($out), "\n"
      if ($out ne "");
}

sub nslookup {
   my ($domain) = @_;
   my ($name, $aliases, $addrtype, $length, @addrs) = gethostbyname($domain);
   my @ip = unpack('C4',$addrs[0]);
   return(join '.', @ip);
}

sub namelookup {
   my ($ip) = @_;
   my @ip = split(/\./,$ip);
   my $addr = pack('C4',@ip);
   my ($name, $aliases, $addrtype, $length, @addrs) = 
       gethostbyaddr($addr,AF_INET);
   return $ip if ($name =~ /^\s*$/);
   return $name;
}
