我需要确定给定的IP地址是否来自某个特殊网络,我必须自动进行身份验证.
Jakarta Commons的网络有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版本来避免这个错误.
使用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); }
来源:这里
你也可以试试
boolean inSubnet = (ip & netmask) == (subnet & netmask);
或更短
boolean inSubnet = (ip ^ subnet) & netmask == 0;