JP Silvashy JP Silvashy - 1 year ago 98
Ruby Question

Rails: find out if an IP is within a range of IPs

This is a tricky one...

How can you tell if an ip, say
is within the range of

Is there a simple Ruby way to do this, or how can I solve this?

Answer Source
>> require "ipaddr"
=> true
>> low ="").to_i
=> 1040187392
>> high ="").to_i
=> 1056964607
>> ip ="").to_i
=> 1050473485
>> (low..high)===ip
=> true

If you are given the network instead of the start and end addresses, it is even simpler

>> net ="")
=> #<IPAddr: IPv4:>
=> true

IPAddr will also work with IPv6 addresses

>> low ='1::')
=> #<IPAddr: IPv6:0001:0000:0000:0000:0000:0000:0000:0000/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>
>> high ='2::')
=> #<IPAddr: IPv6:0002:0000:0000:0000:0000:0000:0000:0000/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>
>> (low..high)'1::1')
=> true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download