用于检查IPv4或IPv6地址是否在给定子网中的Java库

时间:2013-06-10 13:26:09

标签: java ipv6 ipv4 subnet

我可以使用哪个库来检查IP地址是否在给定的子网中?我可以找到像Apache Commons SubnetUtils(SubnetUtils.SubnetInfo.isInRange)这样的库,但是很多都不支持IPv6。

3 个答案:

答案 0 :(得分:8)

edazdarevic's CIDRUtils支持IPv4和IPv6。该示例未提及boolean isInRange(String ipAddress),但它已实现!

另一个选项是java-ipv6,但它不支持IPv4和requires JDK7

答案 1 :(得分:5)

使用spring-security-web' s IpAddressMatcher。与Apache Commons Net不同,它支持ipv4和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);
}

说明

如果您不愿意在项目中加入Spring,请查看我的其他答案,here

答案 2 :(得分:1)

The IPAddress Java library以多态方式支持IPv4和IPv6,并支持子网,包括检查包含子网中地址或子网包含的方法。链接中提供了javadoc。免责声明:我是该图书馆的项目经理。

示例代码:

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));
}

输出:

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