ip 白名單判斷工具類

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

/**
 *
 * ip 白名單校驗
 */
public final class IpWhiteCheckUtil {
    // IP的正則
    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})");
    public static final String DEFAULT_ALLOW_ALL_FLAG = "*";// 允許所有ip標誌位
    public static final String DEFAULT_DENY_ALL_FLAG = "0"; // 禁止所有ip標誌位

    /**
     *
     * getAvaliIpList:(根據IP白名單設置獲取可用的IP列表).
     *
     * @date 2017-4-17 下午02:50:20
     * @param allowIp
     * @return
     */

    private static Set<String> getAvaliIpList(String allowIp) {
        String[] splitRex = allowIp.split(";");// 拆分出白名單正則
        Set<String> ipList = new HashSet<String>(splitRex.length);
        for (String allow : splitRex) {
            if (allow.contains("*")) {// 處理通配符 *
                String[] ips = allow.split("\\.");
                String[] from = new String[] { "0", "0", "0", "0" };
                String[] end = new String[] { "255", "255", "255", "255" };
                List<String> tem = new ArrayList<String>();
                for (int i = 0; i < ips.length; i++)
                    if (ips[i].indexOf("*") > -1) {
                        tem = complete(ips[i]);
                        from[i] = null;
                        end[i] = null;
                    } else {
                        from[i] = ips[i];
                        end[i] = ips[i];
                    }

                StringBuilder fromIP = new StringBuilder();
                StringBuilder endIP = new StringBuilder();
                for (int i = 0; i < 4; i++)
                    if (from[i] != null) {
                        fromIP.append(from[i]).append(".");
                        endIP.append(end[i]).append(".");
                    } else {
                        fromIP.append("[*].");
                        endIP.append("[*].");
                    }
                fromIP.deleteCharAt(fromIP.length() - 1);
                endIP.deleteCharAt(endIP.length() - 1);

                for (String s : tem) {
                    String ip = fromIP.toString().replace("[*]", s.split(";")[0]) + "-"
                            + endIP.toString().replace("[*]", s.split(";")[1]);
                    if (validate(ip)) {
                        ipList.add(ip);
                    }
                }
            } else if (allow.contains("/")) {// 處理 網段 xxx.xxx.xxx./24
                ipList.add(allow);
            } else {// 處理單個 ip 或者 範圍
                if (validate(allow)) {
                    ipList.add(allow);
                }
            }

        }

        return ipList;
    }

    /**
     * 對單個IP節點進行範圍限定
     *
     * @param arg
     * @return 返回限定後的IP範圍,格式爲List[10;19, 100;199]
     */
    private static List<String> complete(String arg) {
        List<String> com = new ArrayList<String>();
        int len = arg.length();
        if (len == 1) {
            com.add("0;255");
        } else if (len == 2) {
            String s1 = complete(arg, 1);
            if (s1 != null)
                com.add(s1);
            String s2 = complete(arg, 2);
            if (s2 != null)
                com.add(s2);
        } else {
            String s1 = complete(arg, 1);
            if (s1 != null)
                com.add(s1);
        }
        return com;
    }

    private static String complete(String arg, int length) {
        String from = "";
        String end = "";
        if (length == 1) {
            from = arg.replace("*", "0");
            end = arg.replace("*", "9");
        } else {
            from = arg.replace("*", "00");
            end = arg.replace("*", "99");
        }
        if (Integer.valueOf(from) > 255)
            return null;
        if (Integer.valueOf(end) > 255)
            end = "255";
        return from + ";" + end;
    }

    /**
     * 在添加至白名單時進行格式校驗
     *
     * @param ip
     * @return
     */
    private static boolean validate(String ip) {
        String[] temp = ip.split("-");
        for (String s : temp)
            if (!pattern.matcher(s).matches()) {
                return false;
            }
        return true;
    }

    /**
     *
     * isPermited:(根據IP,及可用Ip列表來判斷ip是否包含在白名單之中).
     *
     * @date 2017-4-17 下午03:01:03
     * @param ip
     * @param ipList
     * @return
     */
    private static boolean isPermited(String ip, Set<String> ipList) {
        if (ipList.isEmpty() || ipList.contains(ip))
            return true;
        for (String allow : ipList) {
            if (allow.indexOf("-") > -1) {// 處理 類似 192.168.0.0-192.168.2.1
                String[] tempAllow = allow.split("-");
                String[] from = tempAllow[0].split("\\.");
                String[] end = tempAllow[1].split("\\.");
                String[] tag = ip.split("\\.");
                boolean check = true;
                for (int i = 0; i < 4; i++) {// 對IP從左到右進行逐段匹配
                    int s = Integer.valueOf(from[i]);
                    int t = Integer.valueOf(tag[i]);
                    int e = Integer.valueOf(end[i]);
                    if (!(s <= t && t <= e)) {
                        check = false;
                        break;
                    }
                }
                if (check)
                    return true;
            } else if (allow.contains("/")) {// 處理 網段 xxx.xxx.xxx./24
                int splitIndex = allow.indexOf("/");
                // 取出子網段
                String ipSegment = allow.substring(0, splitIndex); // 192.168.3.0
                // 子網數
                String netmask = allow.substring(splitIndex + 1);// 24
                // ip 轉二進制
                long ipLong = ipToLong(ip);
                //子網二進制
                long maskLong=(2L<<32 -1) -(2L << Integer.valueOf(32-Integer.valueOf(netmask))-1);
                // ip與和子網相與 得到 網絡地址
                String calcSegment = longToIP(ipLong & maskLong);
                // 如果計算得出網絡地址和庫中網絡地址相同 則合法
                if(ipSegment.equals(calcSegment))return true;
            }
        }
        return false;
    }

    /**
     *
     * isPermited:(根據IP地址,及IP白名單設置規則判斷IP是否包含在白名單).
     *
     * @date 2017-4-17 下午03:01:37
     * @param ip
     * @param ipWhiteConfig
     * @return
     */
    public static boolean isPermited(String ip, String ipWhiteConfig) {
        if (null == ip || "".equals(ip))
            return false;
        //ip格式不對
        if(!pattern.matcher(ip).matches())return false;
        if (DEFAULT_ALLOW_ALL_FLAG.equals(ipWhiteConfig))
            return true;
        if (DEFAULT_DENY_ALL_FLAG.equals(ipWhiteConfig))
            return false;
        Set<String> ipList = getAvaliIpList(ipWhiteConfig);
        return isPermited(ip, ipList);
    }

    private static long ipToLong(String strIP) {
        long[] ip = new long[4];
        // 先找到IP地址字符串中.的位置
        int position1 = strIP.indexOf(".");
        int position2 = strIP.indexOf(".", position1 + 1);
        int position3 = strIP.indexOf(".", position2 + 1);
        // 將每個.之間的字符串轉換成整型
        ip[0] = Long.parseLong(strIP.substring(0, position1));
        ip[1] = Long.parseLong(strIP.substring(position1 + 1, position2));
        ip[2] = Long.parseLong(strIP.substring(position2 + 1, position3));
        ip[3] = Long.parseLong(strIP.substring(position3 + 1));
        return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
    }

    // 將10進制整數形式轉換成127.0.0.1形式的IP地址
    private static String longToIP(long longIP) {
        StringBuilder sb = new StringBuilder("");
        // 直接右移24位
        sb.append(String.valueOf(longIP >>> 24));
        sb.append(".");
        // 將高8位置0,然後右移16位
        sb.append(String.valueOf((longIP & 0x00FFFFFF) >>> 16));
        sb.append(".");
        sb.append(String.valueOf((longIP & 0x0000FFFF) >>> 8));
        sb.append(".");
        sb.append(String.valueOf(longIP & 0x000000FF));
        return sb.toString();
    }

    public static void main(String[] args) {

//        System.out.println("192.168.0".matches("192.*"));
        System.out.println(IpWhiteCheckUtil.isPermited("127.0.0.1","192.168.4.17"));

        String ipWhilte = "1.168.1.1;" + //設置單個IP的白名單 //
                // "192.*;" //設置ip通配符,對一個ip段進行匹配
                "192.168.3.17-192.168.3.38;" //設置一個IP範圍
                +"192.168.4.0/24"; //設置一個網段
        /*  System.out.println(IpWhiteCheckUtil.checkLoginIP("1.168.1.1",ipWhilte)); //true
          System.out.println(IpWhiteCheckUtil.checkLoginIP("192.168.1.2",ipWhilte)); //false
          System.out.println(IpWhiteCheckUtil.checkLoginIP("192.168.3.16",ipWhilte)); //false
          System.out.println(IpWhiteCheckUtil.checkLoginIP("192.168.3.37",ipWhilte)); //true
          System.out.println(IpWhiteCheckUtil.checkLoginIP("192.168.4.1",ipWhilte));//true
         */

    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章