我希望能够根据两个其他IP范围内的IP返回true/false。
例如:ip 192.200.3.0
range from 192.200.0.0
range to 192.255.0.0
结果应为true。
其他例子:
assert 192.200.1.0 == true
assert 192.199.1.1 == false
assert 197.200.1.0 == false
最佳答案
检查范围的最简单方法可能是将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()
,您可能想要查看Guava库,该库具有InetAddresses帮助程序类,该类避免了DNS查找的可能性。