title: Redis or Mongo for determining if a number falls within ranges?
body: <p>I need a way to quickly check if an IP address falls into one of many forbidden IP ranges.</p>
  
  <p>I currently use iptables to check if the IP falls into a specified range. This works fine for several thousand ranges, but that number is about to increase drastically to several hundred thousand, and will continue to grow.</p>
  
  <p>The other issue with my current method of simply adding new rules to iptables is the increasing number of duplicates.</p>
  
  <p>I need an efficient method for checking if an IP or range falls into an existing (larger) range before it's added to the ruleset.</p>
  
  <p>Ruby is the language I am most familiar with, but what data structures would be the best options for the ever growing number of ranges?</p>
  
  <p>One solution I came up with is to use Redis sets or perhaps MongoDB to store individual IPs as integers, then simply check if the IP exists in the set... but my gut tells me there has to be a smarter way.</p>
  
  <p>If I were to convert IPs into integers and store the ranges, what would be the optimal way to run through the ranges to see if a new IP or range might already be encompassed by an existing bigger range?</p>
  
  <hr>
  
  <p>Final note: speed is more important than memory costs.</p>