seancfoley / IPAddress

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

Ip address contain method fail check #92

Closed syndaez closed 1 year ago

syndaez commented 1 year ago

Hey,

I've noticed that contain method in IPAddress should return all true for these examples, but it returns only one true. Example below:

    public static void main(String[] args) {
        IPAddress address = new IPAddressString("192.168.0.1/24").getAddress();
        System.out.println(address.contains(new IPAddressString("192.168.0.1").getAddress()));
        System.out.println(address.contains(new IPAddressString("192.168.0.2").getAddress()));
        System.out.println(address.contains(new IPAddressString("192.168.0.3").getAddress()));
        System.out.println(address.contains(new IPAddressString("192.168.0.4").getAddress()));
    }

Output:

true
false
false
false

Version: 5.3.4

seancfoley commented 1 year ago

192.168.0.1/24 is the same address as 192.168.0.1. Therefore, 192.168.0.1 does not contain 192.168.0.2, 192.168.0.3, or 192.168.0.4. However, it does contain 192.168.0.1, since it is the same address.

If you want to check a subnet for containment, use the proper network address:

System.out.println(new IPAddressString("192.168.0.0/24").getAddress().
    contains(new IPAddressString("192.168.0.2").getAddress()));

or convert the address to the network address:

System.out.println(new IPAddressString("192.168.0.1/24").getAddress().toPrefixBlock().
    contains(new IPAddressString("192.168.0.2").getAddress()));

If you do that, you will be checking the subnet for containment.

This a duplicate of issue #60, issue #57, issue #54, issue #51, issue #45, issue #40, issue #30, issue #26, and also similar to issue #53 and issue #39.

This is explained in this wiki entry and this entry, see enclosingBlockContains in the latter.

syndaez commented 1 year ago

Sorry then and thank you very much for the explanation.

seancfoley commented 1 year ago

No problem, good luck.