IP白名单校验
支持格式:
? ? 1、127.0.0.1? ? // 指定固定IP
? ? 2、127.0.0.1-127.0.0.128? ? // 可使用“-”來表示一個IP區間,支持跨IP段(一般不會出現這種情況,跨IP段則配置多個規則)
? ? 3、127.0.*? ? // 2~4位IP段可配置為"*"
? ? 注意:“*” 和“-”不允許共存
限制:僅支持ipv4格式的IP,不允許以“localhost”方式訪問
方式:將ip值補全為12位并轉為Long類型,再進行比較
/*** Auther: Charles.Chen <br>* Description: IP 白名單校驗* Date: Create in 18:00 2018/6/19**/ public class IpWhiteListVerify {private static Pattern pattern = Pattern.compile("(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})\\." + "(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})\\."+ "(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})\\." + "(1\\d{1,2}|2[0-4]\\d|25[0-5]|\\d{1,2})");/*** 檢查白名單格式是否正確* @param ip* @return*/public static boolean verifyFormat(String ip) {if(ip == null || ip.trim().length() == 0) {return false;}ip = ip.trim();int allIndex = ip.indexOf("*");int separateIndex = ip.indexOf("-");if(allIndex >= 0 && separateIndex >= 0) {return false;}if(allIndex > 0) {int paddingLength = 4 - ip.split("\\.").length;for(int i=0; i<paddingLength; i++) {ip += ".0";}ip = ip.replace("*", "0");}String[] temp = ip.split("-");for (String s : temp) {if (!pattern.matcher(s).matches()) {return false;}}return true;}/*** 檢查IP是否屬于白名單范圍* @param ip* @param ipList* @return*/public static boolean verifyIp(String ip, List<String> ipList) {if(ipList == null || ipList.size() == 0) {return true;}for(String ips : ipList) {if(ips.indexOf("-") > 0) {String[] ipInterval = ips.split("-");if(isContains(ip, ipInterval[0], ipInterval[1])) {return true;}} else {if(isContains(ip, ips, ips)) {return true;}}}return false;}private static boolean isContains(String ip, String startIp, String endIp) {Long ipValue = ipConversionToLong(ip, true);Long startIpValue = ipConversionToLong(startIp, true);Long endIpValue = ipConversionToLong(endIp, false);if(ipValue >= startIpValue && ipValue <= endIpValue) {return true;}return false;}private static Long ipConversionToLong(String ip, boolean isStart) {String[] ipPassages = ip.split("\\.");int ipPassagesLength = ipPassages.length;String ipValue = "";for(int i=0; i<4; i++) {if(i < ipPassagesLength) {String ipPassage = ipPassages[i];if("*".equals(ipPassage)) {ipValue += isStart ? "000" : "255";} else {ipValue += paddingZero(ipPassage);}} else {ipValue += isStart ? "000" : "255";}}return Long.parseLong(ipValue);}private static String paddingZero(String value) {int paddingZeroLength = 3 - value.length();for(int i=0; i<paddingZeroLength; i++) {value = "0" + value;}return value;} }?
轉載于:https://my.oschina.net/clyy/blog/1832637
總結
- 上一篇: linux添加ip白名单_centOS7
- 下一篇: 防火墙添加ip白名单_如何增加网址白名单