Skip to content

Drop the zone ID when IPAddr#native returns an IPv4 address - #142

Merged
taketo1113 merged 1 commit into
ruby:masterfrom
bardrop-oss:fix-native-drops-zone-id
Nov 22, 2026
Merged

taketo1113 merged 1 commit into
ruby:masterfrom
bardrop-oss:fix-native-drops-zone-id

Conversation

@bardrop

@bardrop bardrop commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

IPAddr#native keeps the IPv6 zone ID when it turns an IPv4-mapped (or IPv4-compatible) address into IPv4:

a = IPAddr.new("::ffff:192.168.1.2%eth0").native
b = IPAddr.new("192.168.1.2")

a.to_s       # => "192.168.1.2"
a.zone_id    # => IPAddr::InvalidAddressError: not an IPv6 address
a == b       # => true
a.eql?(b)    # => false (before), true (after)
[a, b].uniq  # => 2 items (before), 1 item (after)

The zone can't be seen or read on the IPv4 result, but #hash still includes @zone_id, so the two addresses are == but not eql?. Hash keys, Set and #uniq then treat them as different addresses. Python's ipaddress also drops the zone here (IPv6Address("::ffff:192.168.1.2%eth0").ipv4_mapped is IPv4Address('192.168.1.2')).

The fix clears @zone_id in #set when the family becomes AF_INET, which is where #native already narrows the mask to 32 bits. #native on an address that is not mapped or compatible still returns self, so plain IPv6 addresses keep their zone.

Tests: new test_native_drops_zone_id (mapped and compatible forms). It fails before the change and passes after; bundle exec rake test passes (43 tests, 635 assertions).

IPAddr.new("::ffff:192.168.1.2%eth0").native kept the IPv6 zone ID.
The result is IPv4, so the zone is not shown by #to_s and #zone_id
raises, but it is still part of #hash. So the address was == to
IPAddr.new("192.168.1.2") but not #eql?, and Hash, Set and #uniq
treated them as different addresses.
@bardrop
bardrop requested a review from knu as a code owner November 18, 2026 00:38
@taketo1113
taketo1113 merged commit ba992a7 into ruby:master Nov 22, 2026
29 checks passed
@taketo1113

Copy link
Copy Markdown
Collaborator

@bardrop Nice catch! Thank you for the fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants