Code Snippet (Python): Localize your users by IP
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: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):
IP Address = a.b.c.d
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:
Post a Comment