有没有人知道一个java组件来检查IP地址是否来自特定的网络/网络掩码?

我需要确定给定的IP地址是否来自某个特殊网络,我必须自动进行身份validation。

Jakarta Commons Net有org.apache.commons.net.util.SubnetUtils可以满足您的需求。 看起来你做这样的事情:

 SubnetInfo subnet = (new SubnetUtils("10.10.10.0", "255.255.255.128")).getInfo(); boolean test = subnet.isInRange("10.10.10.10"); 

请注意,正如卡森指出的那样,Jakarta Commons Net有一个错误 ,阻止它在某些情况下给出正确的答案。 Carson建议使用SVN版本来避免这个错误。

你也可以试试

 boolean inSubnet = (ip & netmask) == (subnet & netmask); 

或更短

 boolean inSubnet = (ip ^ subnet) & netmask == 0; 

使用Spring的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); } 

来源: 这里

要检查子网中的IP,我在SubnetUtils类中使用了isInRange方法。 但是这种方法有一个错误,如果你的子网是X,每个低于X的IP地址,isInRange都返回true。 例如,如果您的子网是10.10.30.0/24并且您想要检查10.10.20.5,则此方法返回true。 为了处理这个bug我在下面的代码中使用了。

 public static void main(String[] args){ String list = "10.10.20.0/24"; String IP1 = "10.10.20.5"; String IP2 = "10.10.30.5"; SubnetUtils subnet = new SubnetUtils(list); SubnetUtils.SubnetInfo subnetInfo = subnet.getInfo(); if(MyisInRange(subnetInfo , IP1) == true) System.out.println("True"); else System.out.println("False"); if(MyisInRange(subnetInfo , IP2) == true) System.out.println("True"); else System.out.println("False"); } private boolean MyisInRange(SubnetUtils.SubnetInfo info, String Addr ) { int address = info.asInteger( Addr ); int low = info.asInteger( info.getLowAddress() ); int high = info.asInteger( info.getHighAddress() ); return low <= address && address <= high; }