How can I check if an IP address is in a given subnet? I was able to do this by using Apache Commons SubnetUtils (SubnetUtils.SubnetInfo.isInRange) but it does not support IPv6 yet.
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.
Use spring-security-web
'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);
}
Remarks
If you're not willing to include Spring in your project, check out my other answer, here.
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)
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 containing subnet. The javadoc is available at the link. Disclaimer: I am the project manager of that library.
Example code:
contains("10.10.20.0/30", "10.10.20.3");
contains("10.10.20.0/30", "10.10.20.5");
contains("1::/64", "1::1");
contains("1::/64", "2::1");
contains("1::3-4:5-6", "1::4:5");
contains("1-2::/64", "2::");
contains("bla", "foo");
static void contains(String network, String address) {
IPAddressString one = new IPAddressString(network);
IPAddressString two = new IPAddressString(address);
System.out.println(one + " contains " + two + " " + one.contains(two));
}
Output:
10.10.20.0/30 contains 10.10.20.3 true
10.10.20.0/30 contains 10.10.20.5 false
1::/64 contains 1::1 true
1::/64 contains 2::1 false
1::3-4:5-6 contains 1::4:5 true
1-2::/64 contains 2:: true
bla contains foo false
© 2022 - 2024 — McMap. All rights reserved.