2009-02-23 94 views

回答

19

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

注意,如carson指出,雅加达共享网拥有a bug,防止它在某些情况下给出正确的答案。 Carson建议使用SVN版本来避免此错误。

+4

小心使用此。有一个错误会阻止它正常工作。你可能想把它从SVN中取出来。 http://mail-archives.apache.org/mod_mbox/commons-issues/200902.mbox/%[email protected]%3E – carson 2009-02-23 18:43:01

+0

@carson:感谢您的警告。我编辑了我的答案以包含这些信息。 – Eddie 2009-02-23 20:29:29

9

您也可以尝试

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

或更短

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

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

来源:here

0

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

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; 
} 
相关问题