Dec 5, 2006

Code Snippet (Python): Localize your users by IP



On very useful trick if you are developing an international site (and you have local sites) it's to redirect your users to their local site depending on the IP address they are coming from. This is an easy (and optimized) way to do it just with a few lines in Python and mySQL database.

1.- Getting the info:

First of all, we will need the data with all IP-Country information, there are a lot of pay sites offering this feature but i have used this free (reduced version) of one of them.
The data provided by this site is a CSV (comma separated value) file, which we can import into a fully optimized MySQL database ;) (the import method is easily explained in this site )

2.- Working with the Data:

Actually a good way to work/store the IP information is to use the long notation, this notation is represented as:

IP in Long format = 16777216*a + 65536*b + 256*c + d
where:

IP Address = a.b.c.d
Normally in PHP we have ip2long() / long2ip() funtions that help us with the conversion, the Python implementation of this functions , (and here is when the snippet comes):

def ip2long(ip):
splittedaddr = ip.split('.')
ipnum = 16777216*int(splittedaddr[0]) + 65536*int(splittedaddr[1]) + 256*int(splittedaddr[2]) + int(splittedaddr[3])
return ipnum

def long2ip(ipnum):
w = int ( ipnum / 16777216 ) % 256
x = int ( ipnum / 65536 ) % 256
y = int ( ipnum / 256 ) % 256
z = int ( ipnum ) % 256
ip = str(w) + "." + str(x) + "."+ str(y) + "." + str(z)
return ip



By this way and with the help of your IP-Conutry Database we will be able to give our users a personalized assistance ;)

No comments: