Skip to content

Commit dab4c25

Browse files
committed
ntop: Measure address size in bytes
`IPAddr.ntop` takes the binary representation of an 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: #56
1 parent a2a09e3 commit dab4c25

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

lib/ipaddr.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def self.new_ntoh(addr)
111111
# Convert a network byte ordered string form of an IP address into
112112
# human readable form.
113113
def self.ntop(addr)
114-
case addr.size
114+
case addr.bytesize
115115
when 4
116116
addr.unpack('C4').join('.')
117117
when 16

test/test_ipaddr.rb

+10
Original file line numberDiff line numberDiff line change
@@ -134,9 +134,15 @@ def test_s_new_ntoh
134134
def test_ntop
135135
# IPv4
136136
assert_equal("192.168.1.1", IPAddr.ntop("\xC0\xA8\x01\x01"))
137+
assert_equal("192.168.1.1", IPAddr.ntop("\xC0\xA8\x01\x01".b))
138+
assert_equal("10.231.140.171", IPAddr.ntop("\x0A\xE7\x8C\xAB")) # Looks like 2-codepoint string in UTF-8
137139
# IPv6
138140
assert_equal("0000:0000:0000:0000:0000:0000:0000:0001",
139141
IPAddr.ntop("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"))
142+
assert_equal("0000:0000:0000:0000:0000:0000:0000:0001",
143+
IPAddr.ntop("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01".b))
144+
assert_equal("fe80:0000:0000:0000:f09f:9985:f09f:9986",
145+
IPAddr.ntop("\xFE\x80\x00\x00\x00\x00\x00\x00\xF0\x9F\x99\x85\xF0\x9F\x99\x86")) # 10 codepoints in UTF-8
140146

141147
# Invalid parameters
142148
assert_raise(IPAddr::AddressFamilyError) {
@@ -146,6 +152,10 @@ def test_ntop
146152
assert_raise(IPAddr::AddressFamilyError) {
147153
IPAddr.ntop("\xC0\xA8\x01\xFF1")
148154
}
155+
156+
assert_raise(IPAddr::AddressFamilyError) {
157+
IPAddr.ntop("\x0Aあいう") # Four coudepoints in UTF-8
158+
}
149159
end
150160

151161
def test_ipv4_compat

0 commit comments

Comments
 (0)