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
29 changes: 22 additions & 7 deletions lib/ipaddr.rb
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,24 @@ def to_i
return @addr
end

# Returns a string containing the hexadecimal representation of the
# IP address value, right adjusted to the address size.
#
# e.g.:
# require 'ipaddr'
# p IPAddr.new("192.168.1.1").to_hex #=> "c0a80101"
# p IPAddr.new("3ffe:505:2::1").to_hex #=> "3ffe0505000200000000000000000001"
def to_hex
case @family
when Socket::AF_INET
@addr.to_s(16).rjust(8, '0')
when Socket::AF_INET6
@addr.to_s(16).rjust(32, '0')
else
raise AddressFamilyError, "unsupported address family"
end
end

# Returns a string containing the IP address representation.
def to_s
str = _to_string(@addr)
Expand Down Expand Up @@ -268,12 +286,9 @@ def cidr
# Returns a network byte ordered string form of the IP address.
def hton
case @family
when Socket::AF_INET
return [@addr].pack('N')
when Socket::AF_INET6
return (0..7).map { |i|
(@addr >> (112 - 16 * i)) & 0xffff
}.pack('n8')
when Socket::AF_INET, Socket::AF_INET6
value = to_hex
return [value].pack("H#{value.length}")
else
raise AddressFamilyError, "unsupported address family"
end
Expand Down Expand Up @@ -829,7 +844,7 @@ def _reverse
(@addr >> (8 * i)) & 0xff
}.join('.')
when Socket::AF_INET6
return ("%.32x" % @addr).reverse!.gsub!(/.(?!$)/, '\&.')
return to_hex.reverse.chars.join('.')
else
raise AddressFamilyError, "unsupported address family"
end
Expand Down
10 changes: 10 additions & 0 deletions test/test_ipaddr.rb
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,16 @@ def test_to_s_with_zone_id
assert_equal("fe80::1%0012", IPAddr.new("fe80::1%0012").to_s)
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)
assert_equal("ffffffff", IPAddr.new("255.255.255.255").to_hex)
assert_equal("3ffe0505000200000000000000000001", IPAddr.new("3ffe:505:2::1").to_hex)
assert_equal("0123456789abcdef0abcdef012345678", IPAddr.new("123:4567:89ab:cdef:0abc:def0:1234:5678").to_hex)
assert_equal("00000000000000000000000000000000", IPAddr.new("::").to_hex)
assert_equal("ffffffffffffffffffffffffffffffff", IPAddr.new("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff").to_hex)
end

def test_as_json
assert_equal("192.168.1.2", IPAddr.new("192.168.1.2").as_json)
assert_equal("192.168.1.0/24", IPAddr.new("192.168.1.2/24").as_json)
Expand Down
Loading