Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/ipaddr.rb
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,12 @@ def to_string
return _to_string(@addr)
end

# Returns a string containing the IP address representation in
# cidr notation
def cidr
format("%s/%s", to_s, prefix)
end

# Returns a network byte ordered string form of the IP address.
def hton
case @family
Expand Down
8 changes: 8 additions & 0 deletions test/test_ipaddr.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,21 @@ def test_s_new
a = IPAddr.new
assert_equal("::", a.to_s)
assert_equal("0000:0000:0000:0000:0000:0000:0000:0000", a.to_string)
assert_equal("::/128", a.cidr)
assert_equal(Socket::AF_INET6, a.family)
assert_equal(128, a.prefix)

a = IPAddr.new("0123:4567:89ab:cdef:0ABC:DEF0:1234:5678")
assert_equal("123:4567:89ab:cdef:abc:def0:1234:5678", a.to_s)
assert_equal("0123:4567:89ab:cdef:0abc:def0:1234:5678", a.to_string)
assert_equal("123:4567:89ab:cdef:abc:def0:1234:5678/128", a.cidr)
assert_equal(Socket::AF_INET6, a.family)
assert_equal(128, a.prefix)

a = IPAddr.new("3ffe:505:2::/48")
assert_equal("3ffe:505:2::", a.to_s)
assert_equal("3ffe:0505:0002:0000:0000:0000:0000:0000", a.to_string)
assert_equal("3ffe:505:2::/48", a.cidr)
assert_equal(Socket::AF_INET6, a.family)
assert_equal(false, a.ipv4?)
assert_equal(true, a.ipv6?)
Expand All @@ -41,18 +44,21 @@ def test_s_new
a = IPAddr.new("3ffe:505:2::/ffff:ffff:ffff::")
assert_equal("3ffe:505:2::", a.to_s)
assert_equal("3ffe:0505:0002:0000:0000:0000:0000:0000", a.to_string)
assert_equal("3ffe:505:2::/48", a.cidr)
assert_equal(Socket::AF_INET6, a.family)
assert_equal(48, a.prefix)

a = IPAddr.new("0.0.0.0")
assert_equal("0.0.0.0", a.to_s)
assert_equal("0.0.0.0", a.to_string)
assert_equal("0.0.0.0/32", a.cidr)
assert_equal(Socket::AF_INET, a.family)
assert_equal(32, a.prefix)

a = IPAddr.new("192.168.1.2")
assert_equal("192.168.1.2", a.to_s)
assert_equal("192.168.1.2", a.to_string)
assert_equal("192.168.1.2/32", a.cidr)
assert_equal(Socket::AF_INET, a.family)
assert_equal(true, a.ipv4?)
assert_equal(false, a.ipv6?)
Expand All @@ -61,13 +67,15 @@ def test_s_new
a = IPAddr.new("192.168.1.2/26")
assert_equal("192.168.1.0", a.to_s)
assert_equal("192.168.1.0", a.to_string)
assert_equal("192.168.1.0/26", a.cidr)
assert_equal(Socket::AF_INET, a.family)
assert_equal("#<IPAddr: IPv4:192.168.1.0/255.255.255.192>", a.inspect)
assert_equal(26, a.prefix)

a = IPAddr.new("192.168.1.2/255.255.255.0")
assert_equal("192.168.1.0", a.to_s)
assert_equal("192.168.1.0", a.to_string)
assert_equal("192.168.1.0/24", a.cidr)
assert_equal(Socket::AF_INET, a.family)
assert_equal(24, a.prefix)

Expand Down