一、获取登录用户的网络IP
public String getIpAddress(HttpServletRequest request) {String ipAddress = request.getHeader("x-forwarded-for");if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getHeader("Proxy-Client-IP");}if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getHeader("WL-Proxy-Client-IP");}if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getRemoteAddr();}return ipAddress;}
二、在用户表中可以设置ip字段(添加可访问的ip或者ip段)
三、限制IP访问
1.判断表中ip字段中是否存在0.0.0.0 如果存在的话说明允许所有ip访问
2.如果不存在0.0.0.0,则判断ip字段是否存在指定ip段 例如192.168.1.0/24 (如果有的话 则需要判断 当前用户ip是否属于该ip段)
3.如果用户ip不存在于ip段中,则判断ip字段中是否存在单个ip 例如 192.168.1.36
方法一
判断ip字段中是否存在0.0.0.0的方法
参数array数组为我们数据库中存的ip字段的数据 转成数组
target为0.0.0.0
private static boolean containsIPAddress(String[] array, String target) {for (String element : array) {if (element.startsWith(target)) {return true;}}return false;}
方法二
判断用户ip是否存在于ip段以及判断用户ip是否存在于ip字段中
private static boolean isIPInArray(String targetIP, String[] ipArray) {for (String ipOrRange : ipArray) {if (isIPInRange(targetIP, ipOrRange)) {return true;}}return false;}private static boolean isIPInRange(String ipAddress, String ipOrRange) {try {InetAddress inetAddress = InetAddress.getByName(ipAddress);byte[] ipAddressBytes = inetAddress.getAddress();if (!ipOrRange.contains("/")) {InetAddress rangeInetAddress = InetAddress.getByName(ipOrRange);byte[] rangeIpAddressBytes = rangeInetAddress.getAddress();for (int i = 0; i < ipAddressBytes.length; i++) {if (ipAddressBytes[i] != rangeIpAddressBytes[i]) {return false;}}return true;}
使用步骤
ipAddress为获取的登录用户的网络ip
String ipAddress = this.getIpAddress(request); boolean b = containsIPAddress(split, "0.0.0.0");boolean ipInArray = isIPInArray(ipAddress, split);
点赞加关注,持续更新中!!!
如有疑问,可评论,可私信,看到会回复