檢查範圍最簡單的方法可能是將IP地址轉換爲32位整數,然後就比較整數。
public class Example {
public static long ipToLong(InetAddress ip) {
byte[] octets = ip.getAddress();
long result = 0;
for (byte octet : octets) {
result <<= 8;
result |= octet & 0xff;
}
return result;
}
public static void main(String[] args) throws UnknownHostException {
long ipLo = ipToLong(InetAddress.getByName("192.200.0.0"));
long ipHi = ipToLong(InetAddress.getByName("192.255.0.0"));
long ipToTest = ipToLong(InetAddress.getByName("192.200.3.0"));
System.out.println(ipToTest >= ipLo && ipToTest <= ipHi);
}
}
而不是InetAddress.getByName()
,你可能想看看其中有避免DNS查找的可能性的InetAddresses輔助類的番石榴庫。
謝謝,我會嘗試這個 – 2010-11-23 14:17:32