public class IpUtil {
public static boolean isInnerIP(String ipAddress) {
if (ipAddress.equals("0:0:0:0:0:0:0:1") || ipAddress.startsWith("10.") || ipAddress.startsWith("192.168.") || ipAddress.startsWith("127.")) {
return true;
}
long ipNum = getIpNum(ipAddress);
long bBegin = getIpNum("172.16.0.0");
long bEnd = getIpNum("172.31.255.255");
return isInner(ipNum, bBegin, bEnd);
}
private static long getIpNum(String ipAddress) {
String[] ip = ipAddress.split("\\.");
long a = Integer.parseInt(ip[0]);
long b = Integer.parseInt(ip[1]);
long c = Integer.parseInt(ip[2]);
long d = Integer.parseInt(ip[3]);
return a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
}
private static boolean isInner(long userIp, long begin, long end) {
return (userIp >= begin) && (userIp <= end);
}
}
本机测试的时候,ip v6的时候,获取到的是:0:0:0:0:0:0:0:1 ,可以通过更改本机配置实现,这里做了一个兼容判定
|