Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make correct mask when converting IPv4 <=> IPv6 #18

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions lib/ipaddr.rb
Original file line number Diff line number Diff line change
Expand Up @@ -478,17 +478,26 @@ def set(addr, *family)
if addr < 0 || addr > IN4MASK
raise InvalidAddressError, "invalid address: #{@addr}"
end
if @family == Socket::AF_INET6
mask = @mask_addr & IN4MASK
end
when Socket::AF_INET6
if addr < 0 || addr > IN6MASK
raise InvalidAddressError, "invalid address: #{@addr}"
end
if @family == Socket::AF_INET
mask = (IN6MASK ^ IN4MASK) | @mask_addr
end
else
raise AddressFamilyError, "unsupported address family"
end
@addr = addr
if family[0]
@family = family[0]
end
if mask
@mask_addr = mask
end
return self
end

Expand Down
28 changes: 28 additions & 0 deletions test/test_ipaddr.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,25 @@ def test_ipv4_compat
assert_equal("192.168.1.2", b.to_s)
assert_equal(Socket::AF_INET, b.family)
assert_equal(false, b.ipv4_compat?)
assert_equal(32, b.prefix)

a = IPAddr.new("::192.168.0.0/112")
b = a.native
assert_equal("192.168.0.0", b.to_s)
assert_equal(Socket::AF_INET, b.family)
assert_equal(16, b.prefix)

a = IPAddr.new("192.168.1.2")
b = a.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
Expand All @@ -146,11 +160,25 @@ def test_ipv4_mapped
assert_equal("192.168.1.2", b.to_s)
assert_equal(Socket::AF_INET, b.family)
assert_equal(false, b.ipv4_mapped?)
assert_equal(32, b.prefix)

a = IPAddr.new("::ffff:192.168.0.0/112")
b = a.native
assert_equal("192.168.0.0", b.to_s)
assert_equal(Socket::AF_INET, b.family)
assert_equal(16, b.prefix)

a = IPAddr.new("192.168.1.2")
b = a.ipv4_mapped
assert_equal("::ffff: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_mapped
assert_equal("::ffff:192.168.0.0", b.to_s)
assert_equal(Socket::AF_INET6, b.family)
assert_equal(112, b.prefix)
end

def test_reverse
Expand Down