From dc48e0f64eaf7b61f1d7f25c5f7596af61cc038f Mon Sep 17 00:00:00 2001 From: Taketo Takashima Date: Sat, 27 Sep 2025 01:11:39 +0900 Subject: [PATCH] Fix `#ipv4_compat` returning invalid prefix Co-authored-by: Tietew --- lib/ipaddr.rb | 4 +++- test/test_ipaddr.rb | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/ipaddr.rb b/lib/ipaddr.rb index 525466b..1ad7980 100644 --- a/lib/ipaddr.rb +++ b/lib/ipaddr.rb @@ -381,7 +381,9 @@ def ipv4_compat if !ipv4? raise InvalidAddressError, "not an IPv4 address: #{@addr}" end - return self.clone.set(@addr, Socket::AF_INET6) + clone = self.clone.set(@addr, Socket::AF_INET6) + clone.instance_variable_set(:@mask_addr, @mask_addr | 0xffffffffffffffffffffffff00000000) + clone end # Returns a new ipaddr built by converting the IPv6 address into a diff --git a/test/test_ipaddr.rb b/test/test_ipaddr.rb index 7ecd37e..ac8921e 100644 --- a/test/test_ipaddr.rb +++ b/test/test_ipaddr.rb @@ -196,6 +196,13 @@ def test_ipv4_compat } assert_equal("::192.168.1.2", b.to_s) assert_equal(Socket::AF_INET6, b.family) + assert_equal(128, b.prefix) + + a = IPAddr.new("192.168.0.0/16") + b = a.ipv4_compat + assert_equal("::192.168.0.0", b.to_s) + assert_equal(Socket::AF_INET6, b.family) + assert_equal(112, b.prefix) end def test_ipv4_mapped