seancfoley / IPAddress

Java library for handling IP addresses and subnets, both IPv4 and IPv6
https://seancfoley.github.io/IPAddress/
Apache License 2.0
469 stars 63 forks source link

IPv6, Net Mask, contains() #120

Closed matzepf closed 9 months ago

matzepf commented 9 months ago

Sorry, maybe I missed something with IPv6 but why do I get this?

IPAddress address2 = new IPAddressString("1:2:3::0/32").getAddress();
IPAddress address3 = new IPAddressString("1:2:3::0/48").getAddress();
System.out.println(address2.contains(new IPAddressString("1:2:3::12").getAddress()));
System.out.println(address3.contains(new IPAddressString("1:2:3::12").getAddress()));

Output:

false
true

Every net mask < 48 results in false.

seancfoley commented 9 months ago

Firstly, you can write 1:2:3:: instead of 1:2:3::0.

While it is not wrong, there is no need to stick a zero on the end.

What you want is

IPAddress address2 = new IPAddressString("1:2::/32").getAddress();

or

IPAddress address2 = new IPAddressString("1:2:3::/32").getAddress().toPrefixBlock();

1:2:3::/32 is not considered a subnet because its host is not zero, its host is 3:0:0:0:0:0. The subnet is 1:2::/32. 1:2:3::/32 is the same as 1:2:3::, and 1:2:3:: does not contain 1:2:3::12.

This is a duplicate of issue https://github.com/seancfoley/IPAddress/issues/114, issue https://github.com/seancfoley/IPAddress/issues/92, issue https://github.com/seancfoley/IPAddress/issues/60, issue https://github.com/seancfoley/IPAddress/issues/57, issue https://github.com/seancfoley/IPAddress/issues/54, issue https://github.com/seancfoley/IPAddress/issues/51, issue https://github.com/seancfoley/IPAddress/issues/45, issue https://github.com/seancfoley/IPAddress/issues/40, issue https://github.com/seancfoley/IPAddress/issues/30, issue https://github.com/seancfoley/IPAddress/issues/26, issue https://github.com/seancfoley/IPAddress/issues/53 and issue https://github.com/seancfoley/IPAddress/issues/39.

This is explained in this wiki entry and this entry.