`
花太香
  • 浏览: 23466 次
  • 性别: Icon_minigender_1
最近访客 更多访客>>
社区版块
存档分类
最新评论

验证IP是否在范围内

    博客分类:
  • Java
 
阅读更多
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;

}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics