Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if an IP is within a range of IPs

Tags:

ruby

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

like image 344
JP Silvashy Avatar asked Aug 19 '10 02:08

JP Silvashy


People also ask

How can I tell if two IP addresses are on the same network?

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.

How many IP addresses are in a range?

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.


2 Answers

>> 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 
like image 119
John La Rooy Avatar answered Oct 17 '22 08:10

John La Rooy


There is a method #include?

And you can do just:

IPAddr.new("127.0.0.1/8").include? "127.1.10.200"

like image 29
Dmitrii Avatar answered Oct 17 '22 08:10

Dmitrii