diff --git a/lib/ipaddr.rb b/lib/ipaddr.rb index b0df4d3..c840ccb 100644 --- a/lib/ipaddr.rb +++ b/lib/ipaddr.rb @@ -195,6 +195,19 @@ def include?(other) end alias === include? + def private? + # RFC1918: Private Address Space + @@__private_network_class_a ||= self.class.new("10.0.0.0/8") + @@__private_network_class_b ||= self.class.new("172.16.0.0/12") + @@__private_network_class_c ||= self.class.new("192.168.0.0/16") + + return true if @@__private_network_class_a.include?(self) || \ + @@__private_network_class_b.include?(self) || \ + @@__private_network_class_c.include?(self) + + return false + end + # Returns the integer representation of the ipaddr. def to_i return @addr diff --git a/test/test_ipaddr.rb b/test/test_ipaddr.rb index 88b4a01..8a0ec15 100644 --- a/test/test_ipaddr.rb +++ b/test/test_ipaddr.rb @@ -243,6 +243,21 @@ def test_include? end + def test_private? + assert_equal(true, IPAddr.new("10.0.0.0").private?) + assert_equal(true, IPAddr.new("10.255.255.255").private?) + + assert_equal(true, IPAddr.new("172.16.0.0").private?) + assert_equal(true, IPAddr.new("172.31.255.255").private?) + + assert_equal(true, IPAddr.new("192.168.0.0").private?) + assert_equal(true, IPAddr.new("192.168.255.255").private?) + + assert_equal(false, IPAddr.new("192.1.0.0").private?) + assert_equal(false, IPAddr.new("172.32.0.0").private?) + assert_equal(false, IPAddr.new("11.0.0.0").private?) + end + def test_hash a1 = IPAddr.new('192.168.2.0') a2 = IPAddr.new('192.168.2.0')