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
The answer is within something called a Subnet Mask. An IP address is always combined with a Subnet Mask, and it is the Subnet Mask that determines which part of the IP address that belongs to the IP network and which part that belongs to host addresses. The answer is within something called a Subnet Mask.
For IPv4, this pool is 32-bits (232) in size and contains 4,294,967,296 IPv4 addresses. The IPv6 address space is 128-bits (2128) in size, containing 340,282,366,920,938,463,463,374,607,431,768,211,456 IPv6 addresses. A bit is a digit in the binary numeral system, the basic unit for storing information.
>> require "ipaddr" => true >> low = IPAddr.new("62.0.0.0").to_i => 1040187392 >> high = IPAddr.new("62.255.255.255").to_i => 1056964607 >> ip = IPAddr.new("62.156.244.13").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.new("62.0.0.0/8") => #<IPAddr: IPv4:62.0.0.0/255.0.0.0> >> net===IPAddr.new("62.156.244.13") => true
IPAddr
will also work with IPv6 addresses
>> low = IPAddr.new('1::') => #<IPAddr: IPv6:0001:0000:0000:0000:0000:0000:0000:0000/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff> >> high = IPAddr.new('2::') => #<IPAddr: IPv6:0002:0000:0000:0000:0000:0000:0000:0000/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff> >> (low..high)===IPAddr.new('1::1') => true
There is a method #include?
And you can do just:
IPAddr.new("127.0.0.1/8").include? "127.1.10.200"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With