2009-02-23 54 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; 
} 
相關問題