diff --git a/lib/ipaddr.rb b/lib/ipaddr.rb index 59427bc..898af26 100644 --- a/lib/ipaddr.rb +++ b/lib/ipaddr.rb @@ -205,6 +205,30 @@ def to_i return @addr end + # Returns a string containing the binary representation of the + # IP address value, right adjusted to the address size (32 bits + # for IPv4, 128 bits for IPv6), regardless of the prefix length. + # + # e.g.: + # require 'ipaddr' + # p IPAddr.new("192.168.1.1").to_bits + # #=> "11000000101010000000000100000001" + # p IPAddr.new("3ffe:505:2::1").to_bits + # #=> "00111111111111100000010100000101" \ + # # "00000000000000100000000000000000" \ + # # "00000000000000000000000000000000" \ + # # "00000000000000000000000000000001" + def to_bits + case @family + when Socket::AF_INET + @addr.to_s(2).rjust(32, '0') + when Socket::AF_INET6 + @addr.to_s(2).rjust(128, '0') + else + raise AddressFamilyError, "unsupported address family" + end + end + # Returns a string containing the hexadecimal representation of the # IP address value, right adjusted to the address size. # diff --git a/test/test_ipaddr.rb b/test/test_ipaddr.rb index 6af7b73..daa68e6 100644 --- a/test/test_ipaddr.rb +++ b/test/test_ipaddr.rb @@ -304,6 +304,23 @@ def test_to_s_with_zone_id assert_equal("fe80::1%0012", IPAddr.new("fe80::1%0012").to_s) end + def test_to_bits + assert_equal("11000000101010000000000100000001", IPAddr.new("192.168.1.1").to_bits) + assert_equal("00000000000000000000000000000000", IPAddr.new("0.0.0.0").to_bits) + assert_equal("00111111111111100000010100000101" + "00000000000000100000000000000000" + + "00000000000000000000000000000000" + "00000000000000000000000000000001", + IPAddr.new("3ffe:505:2::1").to_bits) + assert_equal("00000001001000110100010101100111" + "10001001101010111100110111101111" + + "00001010101111001101111011110000" + "00010010001101000101011001111000", + IPAddr.new("123:4567:89ab:cdef:0abc:def0:1234:5678").to_bits) + assert_equal("00000000000000000000000000000000" + "00000000000000000000000000000000" + + "00000000000000000000000000000000" + "00000000000000000000000000000000", + IPAddr.new("::").to_bits) + assert_equal("11111111111111111111111111111111" + "11111111111111111111111111111111" + + "11111111111111111111111111111111" + "11111111111111111111111111111111", + IPAddr.new("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").to_bits) + end + def test_to_hex assert_equal("c0a80101", IPAddr.new("192.168.1.1").to_hex) assert_equal("00000000", IPAddr.new("0.0.0.0").to_hex)