It is because include? is treating its argument as an address not as
a network. The subnet mask of the argument is ignored. So
net_2.include?(net_1) is really asking whether the first address of
net_1 (192.168.0.0) is contained in net_2 and that is true.
Makes sense I guess. Is there any way to tell IPAddr to look at it as a
network instead of as an address? I have a situation where I may come
across an address (ending in .0, so defining a network) where the
netmask
isn’t given, so I assign it as a small network (say /29). Later on I
may
come across it again, this time with the netmask defined (say /16), and
I
want to merge the first one into the second one. Therefore, each time I
add
a new network to my database, I compare it to the existing ones to see
if
any should be merged. Any suggestions? Thanks!! – BTR
irb(main):004:0> net_1.include?(net_2)
want to merge the first one into the second one. Therefore, each time I add
a new network to my database, I compare it to the existing ones to see if
any should be merged. Any suggestions? Thanks!! – BTR
You could open up IPAddr to get at the mask for comparison.
On Wed, 2008-01-16 at 14:53 +0900, Bryan R. wrote:
irb(main):004:0> net_1.include?(net_2)
want to merge the first one into the second one. Therefore, each time I add
a new network to my database, I compare it to the existing ones to see if
any should be merged. Any suggestions? Thanks!! – BTR
First I’d like to add that the last octet being 0 does not mean that the
IP address is a network address: In the network 10.0.0.0/25, 10.0.1.0 is
a host address.
IPAddr doesn’t seem to have this functionality, but you can add it like
this:
This works by determining the broadcast address of the network (by ORing
the network address with the reverse netmask) and then checking if both
network and broadcast address are included in the range you’re checking
against.
I believe Felix’s suggestion is the way to go. With yours, the
addresses
could be different, but as long as the mask was bigger it would still
return
true… not correct. Example:
a = IPAddr.new(“192.168.15.5”)
b = IPAddr.new(“192.168.16.0/24”)
I believe Felix’s suggestion is the way to go. With yours, the addresses
could be different, but as long as the mask was bigger it would still return
true… not correct.
This works by determining the broadcast address of the network (by ORing
the network address with the reverse netmask) and then checking if both
network and broadcast address are included in the range you’re checking
against.
This might work too…
class IPAddr
attr_accessor :mask_addr
def network_in_network? ipaddr @mask_addr > ipaddr.mask_addr
end
end
Todd
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.