Java library to check if IPv4 or IPv6 address is i

2019-02-16 13:10发布

问题:

What library can I use to check if an IP address is in a given subnet? I could find libraries like the Apache Commons SubnetUtils (SubnetUtils.SubnetInfo.isInRange) but many do not support IPv6 yet.

回答1:

edazdarevic's CIDRUtils supports both IPv4 and IPv6. The example does not mention boolean isInRange(String ipAddress), but it is implemented!

Another option is java-ipv6, but it does not support IPv4 and requires JDK7.



回答2:

Use Spring's IpAddressMatcher. Unlike Apache Commons Net, it supports both ipv4 and ipv6.

import org.springframework.security.web.util.matcher.IpAddressMatcher;
...

private void checkIpMatch() {
    matches("192.168.2.1", "192.168.2.1"); // true
    matches("192.168.2.1", "192.168.2.0/32"); // false
    matches("192.168.2.5", "192.168.2.0/24"); // true
    matches("92.168.2.1", "fe80:0:0:0:0:0:c0a8:1/120"); // false
    matches("fe80:0:0:0:0:0:c0a8:11", "fe80:0:0:0:0:0:c0a8:1/120"); // true
    matches("fe80:0:0:0:0:0:c0a8:11", "fe80:0:0:0:0:0:c0a8:1/128"); // false
    matches("fe80:0:0:0:0:0:c0a8:11", "192.168.2.0/32"); // false
}

private boolean matches(String ip, String subnet) {
    IpAddressMatcher ipAddressMatcher = new IpAddressMatcher(subnet);
    return ipAddressMatcher.matches(ip);
}


回答3:

commons-ip-math provides support for both IPv4 and IPv6 addresses. Here is how you can check if an IP address is in a given subnet:

Ipv4Range.parse("192.168.0.0/24").contains(Ipv4.parse("10.0.0.1")) 
// false

Ipv6Range.parse("2001:db8::/32").contains(Ipv6.parse("2001:db8::4"))
// true

(disclaimer, I'm one of the maintainers of commons-ip-math)



回答4:

The IPAddress Java library supports both IPv4 and IPv6 in a polymorphic manner and supports subnets, including methods that check for containment of an address or subnet in a subnet. The javadoc is available at the link.

Here is sample code that solves your problem, which works identically with either IPv4 or IPv6.