IP-geolocation

Example of getting geolocation information of IP's via free ipinfodb service

The code below is run from the command line with the ip as argument.

#!/bin/tclsh

package require http
package require JSONRPC

set ip $argv
puts "get geo data from $argv"

#get the desired data
set ht [::http::geturl http://ipinfodb.com/ip_query.php?output=json&timezone=false&ip=$ip]
set geo_ip [json::json2dict [::http::data $ht]]
::http::cleanup $ht

# some sample processing stuff
if {[dict get $geo_ip Status] == "OK"} {
    foreach key [dict keys $geo_ip] {
        set value [dict get $geo_ip $key]
        if {$value != ""} {
            puts "$key => $value"
        }
    }
}

Sample session:

 rob@rob-desktop:~/Public$ ./ip-geo 70.85.16.128
 get geo data from 70.85.16.128
 Ip => 70.85.16.128
 Status => OK
 CountryCode => US
 CountryName => United States
 RegionCode => 48
 RegionName => Texas
 City => Houston
 ZipPostalCode => 77002
 Latitude => 29.7523
 Longitude => -95.367

you can also do this easily using the tcllib rest module

 package require rest

 set geoip(lookup) {
   url http://ipinfodb.com/ip_query.php 
   req_args { ip: }
   static_args { output json timzone false }
 }

 rest::create_interface geoip

 array set out geoip::lookup -ip 70.85.16.128
 parray out

DKF: You can fetch XML (parse with tdom) by omitting the output parameter.