[BangPypers] Country look up for an IP address

Chetan Nichkawde chetan.nichkawde at gmail.com
Thu Feb 19 19:49:02 CET 2009

Hi Pradeep,

   I haven't done much of django. Looking at this line of your code :-

iptc = session.query(c.IPToCountry).selectfirst(and_(c.IPToCountry.c.ip_from
= ip))

If I understand the above database query correctly, you are doing an exact
match of input IP with ip_from field. There is a range of IP address
(translated to 32 bit integer) which map to a country. So, the input IP may
fall within a any range. So where clause of query should be ip_from <= ip <=

Having done the above correction. Suppose you build indexes on both ip_from
and ip_to fields. Databases provide two kind of indexes. B-tree indexes and
hash index. B-tree is very much similar to binary search tree except that
each node has several elements (the number being proportional to the size of
disk block on the system). B-tree data structure is static in nature and it
is not self adjusting like splay tree where recently accessed elements move
near the root of the tree. Moreover, your entire data resides on the disk
rather than being in memory. Disk access is order of magnitude slower memory
access. Hash index is also static in nature and has problem of collisions. 

A query like ip_from <= ip <= ip_to would involve range search which B+ tree
best provides. It would be search on two indexes i.e ip_from and ip_to and
would be accessing data from the disk, would not be self adjusting and hence
would be much much slower than the splay tree implementation which is
optimized (look at the code) for this kind of country look up for given IP

Hope, I answer your question.


Pradeep Gowda wrote:
> I'm curious.. What is the advantage of doing this over using a database?
> I did this back in 2006 using a DB.
> URL :
> http://pradeepgowda.com/programming/ip-to-country-for-pylons-comments
> +PG
> On Thu, Feb 19, 2009 at 5:21 AM, Chetan Nichkawde
> <chetan.nichkawde at gmail.com> wrote:
>> Dear BangPypers,
>>    There was a problem posed to me to efficiently find the country for a
>> given IP address. I have devised the solution for the same using splay
>> tree.
>> This could used in various places, like serving a web pages based on the
>> country from which the request is coming from. The code can be downloaded
>> from
>> http://code.google.com/p/ip-country-translator/
>> Chetan
>> _______________________________________________
>> BangPypers mailing list
>> BangPypers at python.org
>> http://mail.python.org/mailman/listinfo/bangpypers
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers

View this message in context: http://www.nabble.com/Country-look-up-for-an-IP-address-tp22097473p22107174.html
Sent from the BangPypers - Bangalore Python Users Group mailing list archive at Nabble.com.

More information about the BangPypers mailing list