08-01
29

关于java 的 split 点 “.” IP限制类 源码

/**
    java split . 要用 [.]
    例如ip地址 或 包
*/
// IP限制类 源码
public class IPUtils {

    public static int[] IPsplit(String ip) {
        return IPsplit(ip,false);
    }
    /**
     * reutrn a int array with 4 size
     *
     * @param ip
     * @return
     */
    public static int[] IPsplit(String ip,boolean max) {
        int[] inum = new int[4];
        try {
            String[] nums = ip.split("[.]");
            int len =nums.length;
            for (int i = 0; i < len; i++) {
                inum[i] = Integer.parseInt(nums[i]);
            }
            if(max) {//if max ,fill 256 to int[]
                if(len<inum.length) {
                    for (int j = len; j < inum.length; j++) {
                        inum[j]=256;
                    }
                }
            }
        } catch (Exception e) {
        }
        return inum;
    }

    public static boolean isBetween(String myIP, String ip) {
        return isBetween(myIP, ip, ip);
    }

    /**
     * return myIP is between ip1~ip2
     *
     * @param myIP
     * @param ip1
     * @param ip2
     * @return
     */
    public static boolean isBetween(String myIP, String ip1, String ip2) {
        if (myIP == null) {
            return true;
        }
        if (null == ip1) {
            ip1 = "0.0.0.0";
        }
        if (null == ip2) {
            ip2 = "256.0.0.0";
        }
        int[] myIPs = IPsplit(myIP);

        return arraySub(myIPs, IPsplit(ip2,true)) && arraySub(IPsplit(ip1), myIPs);
    }

    private static boolean arraySub(int[] a, int[] b) {
        for (int i = 0; i < a.length; i++) {
            if (b[i] - a[i] > 0) {
                return true;
            } else if (b[i] - a[i] < 0) {
                return false;
            } else {
                if(i+1==a.length) {//check is end
                    return true;
                }else {
                    continue;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        String myIP = "61.52.31.68";
        String ip1 = "61.52.31.68";
        String ip2 = "61.52.31.68";
        System.out.println(isBetween(myIP, ip1,ip2));

    }

}

文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: IP 限制 split
相关日志:
评论: 0 | 引用: 0 | 查看次数: 1197
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭