user1071840
user1071840

Reputation: 3592

How to test if an ipv6 addres matches a network prefix

I've to test if an "IPv4 mapped address" matches some ipv6 network prefix like this 2001:db8::/32.

I've read related link 1 and related link 2 and I understand how we can test if an address lies in a subnet.

I don't know if those links will be relevant in my context. In my understanding we can create a 128bit IPv6 address with the wire format of a "mapped" address, and transmit it in an IPv6 packet header. However, Java's InetAddress creation methods appear to adhere doggedly to the original intent of the "mapped" address: all "mapped" addresses return Inet4Address objects.

If I want to run the isInSubnet test like this:

 boolean inSubnet = (ip ^ subnet) & netmask == 0;

For this kind of test, I've to convert the ip, subnet and netmask to integers or longs. But, will this test work if the subnet and netmask were expressed as IPV6 values and ip was coerced to be an Inet4Address value?

Upvotes: 1

Views: 1516

Answers (2)

Sean F
Sean F

Reputation: 4615

Given the ipv4 address 1.2.3.4, the ipv4 mapped address is ::ffff:1.2.3.4 which always has the prefix 0::ffff:0:0/96

In any case, in general for testing if an ipv6 address is in a given subnet, you can use the open-source IPAddress Java library which can do ip address manipulation such as conversion to/from ipv4/ipv6 and subnet checking Disclaimer: I am the project manager.

Example code:

    String ipv6 = "2001:db8:57AB:0000:0000:0000:0000:0001";
    String ipv6subnet = "2001:db8::/32";
    String ipv4 = "1.2.3.4";
    try {
        IPAddressString ipv6addrstr = new IPAddressString(ipv6);
        IPAddressString ipv6addrsubnetstr = new IPAddressString(ipv6subnet);
        IPAddressString ipv4addrstr = new IPAddressString(ipv4);

        IPAddress ipv6addr = ipv6addrstr.toAddress();
        IPAddress ipv6addrsubnet = ipv6addrsubnetstr.toAddress();
        IPAddress ipv4mappedaddr = ipv4addrstr.toAddress().toIPv6();

        System.out.println(ipv6addrsubnet + " contains " + ipv6addr + " is " + ipv6addrsubnet.contains(ipv6addr)); //
        System.out.println(ipv6addrsubnet + " contains " + ipv4mappedaddr + " is " + ipv6addrsubnet.contains(ipv4mappedaddr)); //

    } catch(AddressStringException e) {
        //e.getMessage has validation error
    }

output:

2001:db8:0:0:0:0:0:0/32 contains 2001:db8:57ab:0:0:0:0:1 is true
2001:db8:0:0:0:0:0:0/32 contains 0:0:0:0:0:ffff:102:304 is false

Upvotes: 0

JVXR
JVXR

Reputation: 1322

If you have the luxury to do so, I'd suggest that you use google inetaddresses class. It offers some nice features that you can use to coerce to IPv4 and what not.

Upvotes: 0

Related Questions