store ip ranges in Redis

store ip ranges in Redis

It depends if you consider your IP ranges can overlap or not. If not, the solution is quite simple:

      use a collection of hash to store providers data
      use a zset to index the max value of your ranges
      retrieve the (unique) range whose max value is greater than an IP
      check the the min value of this range is lower than the IP


Here are my providers. Each of them are identified with an id. Please note I could add more properties attached to each provider:

hmset providers:1 name P1 min 3232235786 max 3232235826
hmset providers:2 name P3 min 1232235786 max 1232235826
hmset providers:3 name P3 min 2232235786 max 2232235826
hmset providers:4 name P4 min 4232235786 max 4232235826

Each time a provider is added in the system, an index must be maintained (manually: this is Redis, not a relational database). Score is the max value, member is the id of the range.

zadd providers:index 3232235826 1 1232235826 2 2232235826 3 4232235826 4
(integer) 4
zrange providers:index 0 -1
1) "2"
2) "3"
3) "1"
4) "4"

Now to query the unique range corresponding to an IP address, you need 2 roundtrips:

zrangebyscore providers:index 3232235787 +inf LIMIT 0 1
1) "1"
hgetall providers:1
1) "name"
2) "P1"
3) "min"
4) "3232235786"
5) "max"
6) "3232235826"

Then the client program just has to check that your IP is greater or equal than the minimum address of the returned range.