IP-to-Country lookup, for free and 95% accurate

April 21, 2009 by AcidRaZor · Leave a Comment
Filed under: JavaScript, Programming 101 

One of my recent posts showed you how to convert an IP address to an IP number so you could do a lookup on a IP-to-Country database.

However, I’ve found the next best thing. Maxmind.com is one of the leaders in GeoIP location and sports a database that is more than 99% accurate. That’s the paid version. For my project though, I only needed to know the country, and had to be pretty accurate.

Welcome Maxmind’s free JavaScript addon API! 95% accurate and does what I want it to do.

1
2
3
<script type="text/javascript" src="http://j.maxmind.com/app/country.js"></script>
var countryCode = geoip_country_code();
alert(countryCode);

And that’s IT! You don’t have to host the database, you don’t have to do the number conversion yourself and pretty much everything else is taken care for you. The free service also included City lookups! Include and enjoy!

Here’s the link to their site: http://www.maxmind.com/app/javascript_city

IP to Country – Convert IP Address to IP Number

April 15, 2009 by AcidRaZor · 2 Comments
Filed under: SQL Server 

Here is a simple SQL Statement that you can use in a stored procedure to determine the IP number of an IP address to compare with any IP to Country database:

1
2
3
4
5
6
7
8
9
10
11
12
DECLARE @ip VARCHAR(15),@1st INT,@2nd INT,@3rd INT,@4th INT
 
SET @ip = '41.243.224.9'
SELECT @1st = LEFT(@ip,CHARINDEX('.',@ip)-1)
SET @ip = RIGHT(@ip,LEN(@ip)-CHARINDEX('.',@ip))
SELECT @2nd = LEFT(@ip,CHARINDEX('.',@ip)-1)
SET @ip = RIGHT(@ip,LEN(@ip)-CHARINDEX('.',@ip))
SELECT @3rd = LEFT(@ip,CHARINDEX('.',@ip)-1)
SET @ip = RIGHT(@ip,LEN(@ip)-CHARINDEX('.',@ip))
SELECT @4th = @ip
 
SELECT ((@4th)+(@3rd*256)+(@2nd * 65536)+(@1st * 16777216))

This allows you to have a SQL procedure take the variable of an IP address and not have to convert the IP address in code first. This should work for MySQL as well with minor changes.

The formula is pretty simple and self-explanatory. As soon as I find a reliable (mostly complete) IP to Country database, I will edit this post to reflect it, thus far I haven’t found any to even pick up the address range my country is in which is a real shame. Not even the open source PHP project ip2c can pick it up, which makes me doubt it’s ability to help in any program developed to determine the country automatically from the IP address.

SEO Powered by Platinum SEO from Techblissonline