2009-02-23 7 views

답변

19

Jakarta Commons Net은 귀하의 요구를 충족시키는 것으로 보입니다.

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

+0

@carson : 경고 해 주셔서 감사합니다. 이 정보를 포함하도록 내 대답을 편집했습니다. – Eddie

9

또한

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

ip와 netmask는 int 또는 long입니까? – simgineer

+0

32 비트 주소 인 IPv4는 int입니다. 나는 IPv6가 64 비트 값이라고 의심하지만, 나는 스스로 헴을 사용하지 않았다. –

3

사용 봄의 IpAddressMatcher

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

이하를 시도 할 수 있습니다. 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 일 경우 isInRange가 true를 반환하는 X보다 낮은 모든 IP 주소를 버그로 처리합니다. 예를 들어 서브넷이 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; 
} 
관련 문제