Skip to content

Commit

Permalink
Make IPAddr#include? consider range of argument
Browse files Browse the repository at this point in the history
It would be nice to use Range#cover? here, but it doesn't work
correctly before Ruby 2.6. Switch to manual checks of the beginning
of end of the ranges.

Fixes Ruby Bug 14119
  • Loading branch information
jeremyevans committed Mar 6, 2020
1 parent 283d16f commit f45630d
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 25 deletions.
31 changes: 6 additions & 25 deletions lib/ipaddr.rb
Original file line number Diff line number Diff line change
Expand Up @@ -168,34 +168,15 @@ def mask(prefixlen)
# net1 = IPAddr.new("192.168.2.0/24")
# net2 = IPAddr.new("192.168.2.100")
# net3 = IPAddr.new("192.168.3.0")
# net4 = IPAddr.new("192.168.2.0/16")
# p net1.include?(net2) #=> true
# p net1.include?(net3) #=> false
# p net1.include?(net4) #=> false
# p net4.include?(net1) #=> true
def include?(other)
other = coerce_other(other)
if ipv4_mapped?
if (@mask_addr >> 32) != 0xffffffffffffffffffffffff
return false
end
mask_addr = (@mask_addr & IN4MASK)
addr = (@addr & IN4MASK)
family = Socket::AF_INET
else
mask_addr = @mask_addr
addr = @addr
family = @family
end
if other.ipv4_mapped?
other_addr = (other.to_i & IN4MASK)
other_family = Socket::AF_INET
else
other_addr = other.to_i
other_family = other.family
end

if family != other_family
return false
end
return ((addr & mask_addr) == (other_addr & mask_addr))
range = to_range
other = coerce_other(other).to_range
range.begin <= other.begin && range.end >= other.end
end
alias === include?

Expand Down
2 changes: 2 additions & 0 deletions test/test_ipaddr.rb
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,8 @@ def test_include?
assert_equal(true, net1.include?(IPAddr.new("192.168.2.0")))
assert_equal(true, net1.include?(IPAddr.new("192.168.2.255")))
assert_equal(false, net1.include?(IPAddr.new("192.168.3.0")))
assert_equal(true, net1.include?(IPAddr.new("192.168.2.0/28")))
assert_equal(false, net1.include?(IPAddr.new("192.168.2.0/16")))
# test with integer parameter
int = (192 << 24) + (168 << 16) + (2 << 8) + 13

Expand Down

0 comments on commit f45630d

Please sign in to comment.