How to check if an IP address is from a particular network/netmask in Java?

后端 未结 7 2183
北恋
北恋 2020-11-29 23:33

I need to determine if given IP address is from some special network in order to authenticate automatically.

7条回答
  •  遥遥无期
    2020-11-30 00:04

    I know this is very old question, but I stumbled upon this when I was looking to solve the same problem.

    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 (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 = "192.168.1.0";
            Ipv4 ipv41 = Ipv4.parse(input1);
    
            // Using CIDR notation to specify the networkID and netmask
            Ipv4Range range = Ipv4Range.parse("192.168.0.0/24");
            boolean result = range.contains(ipv41);
            System.out.println(result); //false
    
            String input2 = "192.168.0.251";
            Ipv4 ipv42 = Ipv4.parse(input2);
    
            // Specifying the range with a start and end.
            Ipv4 start = Ipv4.of("192.168.0.0");
            Ipv4 end = Ipv4.of("192.168.0.255");
            range = Ipv4Range.from(start).to(end);
    
            result = range.contains(ipv42); //true
            System.out.println(result);
    

提交回复
热议问题