验证IP是否在范围内

public class IpUtil {

/**
* 验证IP是否在范围内。
*
* @param ip
*            子网
* @param mask
*            子网掩码
* @param clientIp
*            需要验证的IP
* @return
*/
public static boolean isInRange(String ip, int mask, String clientIp) {
byte maskByte = Byte.parseByte(String.valueOf(mask));
int intMask = ~((1 << (32 - maskByte)) - 1);
int intIp = convertIp2Int(ip);
int intClientIp = convertIp2Int(clientIp);
return ((intIp & intMask) == (intClientIp & intMask));
}

private static int convertIp2Int(String ipAddress) {
int result = 0;
Inet4Address i4ip = null;
try {
i4ip = (Inet4Address) InetAddress.getByName(ipAddress);
} catch (UnknownHostException e) {
e.printStackTrace();
}
if (null != i4ip) {
byte[] temp = i4ip.getAddress();
result = (temp[0] << 24) | ((temp[1] & 0xFF) << 16)
| ((temp[2] & 0xFF) << | (temp[3] & 0xFF);
}
return result;

}

}

猜你喜欢

转载自hospop.iteye.com/blog/1845578
今日推荐