Equality of IPv4 mapped IPv6 addresses and their IPv4 equivalents

I have two dependencies which give me the same IP address in different formats - one is Ipv4Addr, the other is the same address represented as an IPv4 mapped IPv6 address in a Ipv6Addr. I need to test if they're the same address but this fails:

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;

fn main() {
    let normal_ipv4_address = IpAddr::V4(Ipv4Addr::from_str("10.255.3.5").unwrap());
    let ipv6_mapped_address = IpAddr::V6(Ipv6Addr::from_str("::ffff:10.255.3.5").unwrap());

    assert!(normal_ipv4_address.eq(&ipv6_mapped_address))
}

What's the best way to assert that these are, in fact, the same address (without using the nightly-only to_canonical function on the Ipv6Addr)?

I suspect you'll need to convert them to both be the same kind of address (v4 vs v6). There are several methods to do this, described in the IPv4-mapped IPv6 Addresses section of the docs:

To convert from an IPv4 address to an IPv4-mapped IPv6 address, use Ipv4Addr::to_ipv6_mapped. Use Ipv6Addr::to_ipv4 to convert an IPv4-mapped IPv6 address to the canonical IPv4 address. Note that this will also convert the IPv6 loopback address ::1 to 0.0.0.1 . Use Ipv6Addr::to_ipv4_mapped to avoid this.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.