#!/usr/bin/perl

use Socket;

if ($ARGV[0]) {
	print findip($ARG[0])."\n";
} else {
	print "Usage:\n";
}

sub findip {
	my $ipnr = shift;
	my $iaddr = inet_aton($ipnr);
	my $name  = gethostbyaddr($iaddr, AF_INET);
	if(not $name) {
		# No DNS for this. Try traceroute
		#my @traceroute = `mtr --report -c 1 $ipnr`;
		my @traceroute = `traceroute $ipnr`;
		for (reverse @traceroute) {
			print "BAR: $_";
			# Take the last hop that resolves
			/^\d+\.\d+\.\d+\.\d+\s*/ and next;
			/^\?\?\?/ and next;
			chomp;
			/^(\S+)/ || die;
			$router=$1;
			print "FOO $router\n";
			$router=~/^HOST/ and next; # Bug in mtr sometimes gives nothing
			$name="traceroute/$ipnr/$1" and last;
		}
	}
	if($name=~s/\.?([^.]+)\.([^.]+)$//) {
		$domain = $1; $country = $2;
		return "'$name', IPdomain='$domain', IPcountry='$country'";
	} else {
		warn("$name does not have domain");
	}
}
