Skip to content

Commit

Permalink
ntop: Measure address size in bytes
Browse files Browse the repository at this point in the history
`IPAddr.ntop` takes a binary representation of IP address, whose
length should be 4 or 16 *bytes* (not characters/codepoints).

This patch fixes the bug that `IPAddr.ntop` doesn't handle Strings in
a multibyte encoding correctly.

Fixes: ruby#56
  • Loading branch information
hanazuki committed Nov 27, 2023
1 parent a2a09e3 commit 1c365c3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/ipaddr.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def self.new_ntoh(addr)
# Convert a network byte ordered string form of an IP address into
# human readable form.
def self.ntop(addr)
case addr.size
case addr.bytesize
when 4
addr.unpack('C4').join('.')
when 16
Expand Down
10 changes: 10 additions & 0 deletions test/test_ipaddr.rb
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,15 @@ def test_s_new_ntoh
def test_ntop
# IPv4
assert_equal("192.168.1.1", IPAddr.ntop("\xC0\xA8\x01\x01"))
assert_equal("192.168.1.1", IPAddr.ntop("\xC0\xA8\x01\x01".b))
assert_equal("10.231.140.171", IPAddr.ntop("\x0A\xE7\x8C\xAB")) # Looks like 2-codepoint string in UTF-8
# IPv6
assert_equal("0000:0000:0000:0000:0000:0000:0000:0001",
IPAddr.ntop("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"))
assert_equal("0000:0000:0000:0000:0000:0000:0000:0001",
IPAddr.ntop("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01".b))
assert_equal("fe80:0000:0000:0000:f09f:9985:f09f:9986",
IPAddr.ntop("\xFE\x80\x00\x00\x00\x00\x00\x00\xF0\x9F\x99\x85\xF0\x9F\x99\x86")) # 10 codepoints in UTF-8

# Invalid parameters
assert_raise(IPAddr::AddressFamilyError) {
Expand All @@ -146,6 +152,10 @@ def test_ntop
assert_raise(IPAddr::AddressFamilyError) {
IPAddr.ntop("\xC0\xA8\x01\xFF1")
}

assert_raise(IPAddr::AddressFamilyError) {
IPAddr.ntop("\x0Aあいう") # Four coudepoints in UTF-8
}
end

def test_ipv4_compat
Expand Down

0 comments on commit 1c365c3

Please sign in to comment.