Validate an IP Address (with Mask)

后端 未结 6 1514
一整个雨季
一整个雨季 2021-02-01 09:52

I have ip addresses and a mask such as 10.1.1.1/32. I would like to check if 10.1.1.1 is inside that range. Is there a library or utility that would do

6条回答
  •  借酒劲吻你
    2021-02-01 10:04

    There is commons-ip-math library that I believe does a very good job. Please note that as of May 2019, there hasn't been any updates to the library for 2 years (Could be that its already very mature library). Its available on maven-central

    It supports working with both IPv4 and IPv6 addresses. Their brief documentation has examples on how you can check if an address is in a specific range for IPv4 and IPv6

    Example for IPv4 range checking:

            String input1 = "10.1.1.1";
            Ipv4 ipv41 = Ipv4.parse(input1);
    
            // Using CIDR notation to specify the networkID and netmask
            Ipv4Range range = Ipv4Range.parse("10.1.1.1/32");
            boolean result = range.contains(ipv41);
            System.out.println(result); //true
    
            String input2 = "10.1.1.1";
            Ipv4 ipv42 = Ipv4.parse(input2);
    
            // Specifying the range with a start and end.
            Ipv4 start = Ipv4.of("10.1.1.1");
            Ipv4 end = Ipv4.of("10.1.1.1");
            range = Ipv4Range.from(start).to(end);
    
            result = range.contains(ipv42); //true
            System.out.println(result);
    

提交回复
热议问题