I needed a very fast and effective way of fining geographical location of an IP address. I’ve already implemented a very nice interface located at Dayana Host IP Location, but due to web based system it’s not fast enough for what I need.
Basically I’m trying to block access to login to certain mail boxes (managed by exim) from some countries. Routine is in Perl, so I can easily find IP address of a host using DNS lookup. All I needed was a service to give the location based on incoming IP address. I used rbldnsd and modified it to accept MaxMind country database and wola, it works as expected.
To use, first reverse the IP, just like what you do with RBL based spam lists. For instance 204.50.14.1 will be 1.14.50.204, then combine it with .rbloc.dayanadns.com and make a DNS query to find IP address, for example:
$host 1.14.50.204.rbloc.dayanadns.com
That will give you two records, an A record and a TXT record.
‘A’ record will be in form of 127.0.X.Y wherre X is the ASCII code of the first letter of country code and Y is the second letter. For our example returned IP is 127.0.67.65 which means ‘CA’ (C=> 67, A=>65).
TXT record is the complete country name, i.e. ‘Canada’.
Here is a sample perl script to get the country code:
#!/usr/bin/perl use Socket; $packed_ip = gethostbyname('1.14.50.204.rbloc.dayanadns.com'); if (defined $packed_ip) { $ip_address = inet_ntoa($packed_ip); my(undef, undef, $d1, $d2) = split(/\./, $ip_address); $country_code = chr($d1).chr($d2); } print "Result address: ".$ip_address."\n"; print "Country code: ".$country_code."\n";
and this one is in PHP:
<?php $ip_address = gethostbyname('1.14.50.204.rbloc.dayanadns.com'); list($d1,$d2,$d3,$d4) = explode('.',$ip_address); $country_code = chr($d3).chr($d4); print "Result address: ".$ip_address."\n"; print "Country code: ".$country_code."\n"; ?>