/**
* 判断 IP 是否在这个 IP 段中。IP 段需要使用 ~ 或 - 进行分隔
*
* @param ip IP
* @param ipSegment IP 段。例如 192.168.1.58 ~ 192.168.1.91。
*/
public boolean isInIpSegment(String ip, String ipSegment) throws UnknownHostException {
BigInteger addr;
try {
addr = new BigInteger(InetAddress.getByName(ip).getAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
throw new UnknownHostException("错误的 IP");
}
String[] split;
if (ipSegment.contains("~")) {
split = ipSegment.split("~");
} else if (ipSegment.contains("-")) {
split = ipSegment.split("-");
} else {
throw new IllegalArgumentException("IP段不正确");
}
BigInteger lowIp = new BigInteger(InetAddress.getByName(split[0].trim()).getAddress());
BigInteger highIp = new BigInteger(InetAddress.getByName(split[1].trim()).getAddress());
return addr.compareTo(lowIp) >= 0 && addr.compareTo(highIp) <= 0;
}