Saturday, April 26, 2008

IP Geolocation


#!/usr/bin/perl
# IP geolocation by nwo.
#
# the first database is frighteningly accurate when it locates an IP.
# it was off by approximately 2 blocks from my house when I looked up mine.
#
# 10/26/2007

use Socket;

sub resolv {
local($host) = @_;
$address = inet_ntoa(inet_aton($host));
return($address);
}

$ip = $ARGV[0];

if($ip =~ /\w+/) {
$host = $ip;
$ip = &resolv($ip);
}

open(F, "lynx -dump http://api.hostip.info/get_html.php?ip=$ip\|") || die "$!";
while() {

if(/^Country:\s+(.*)/) {
$country = $1;
next;
}

if(/^City:\s+(.*)/) {
$city = $1;
next;
}
}
print "\n\n";
print "+-- Detailed location attempt --+\n";
print "Information for: $ip ($host)\n";
print "Best guess: $city - $country\n";
print "\n\n";
close(F);

open(F, "lynx -dump http://netgeo.caida.org/perl/netgeo.cgi?target=$ip|") || die "$!";
while() {
if(/^.*?CITY:\s+(.*)/) {
$city = $1;
if($city eq "") { $city = "unknown"; }
next;
}
if(/^.*?STATE:\s+(.*)/) {
$state = $1;
if($state eq "") { $state = "unknown"; }
next;
}
if(/^.*?COUNTRY:\s+(.*)/) {
$country = $1;
if($country eq "") { $country = "unknown"; }
next;
}
if(/^.*?DOMAIN_GUESS:\s+(.*)/) {
$domain = $1;
if($domain eq "") { $domain = "unknown"; }
next;
}
}
print "+-- Guessed location. --+\n";
print "Location: $city, $state - $country\n";
print "Domain: $domain\n";
print "\n\n";

No comments: