How can you tell if an ip, say 62.156.244.13
is within the range of 62.0.0.0
and 62.255.255.255
I prefer this approach for converting the IP address to an integer for range comparison:
# n_ip("192.1.1.23") will return the number 192001001023
def n_ip(input)
input.split(".").collect{|p| p.rjust(3, "0")}.join.to_i
end
def ip_in_range?(from, to, given)
(n_ip(from)..n_ip(to).include?(n_ip(given))
end
Now you can check the value as follows:
>> ip_in_range?("192.168.0.0", "192.168.0.255","192.168.0.200")
ip_in_range?("192.168.0.0", "192.168.0.255","192.168.0.200")
=> true
>> ip_in_range?("192.168.0.0", "192.168.0.255", "192.168.1.200")
ip_in_range?("192.168.0.0", "192.168.0.255", "192.168.1.200")
=> false
The integer returned is not a 32 bit representation of the IP address. The logic will work for all valid IP addresses.