ip校验方法:判断ip是否位于指定的范围内

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IPvalidate
{
   
    /**
     * @param args
     */
    public static void main(String[] args)
    {
        //存放ip对象的list,ip对象包含:开始段、结束段
        List<IpDo> ipList = new ArrayList<IpDo>();
       
        //第一行ip段
        IpDo ipDo = new IpDo();
        ipDo.setBeginIp("10.166.37.0");
        ipDo.setEndIp("10.166.37.180");
        ipList.add(ipDo);
        //第二行ip段
        IpDo ipDo2 = new IpDo();
        ipDo2.setBeginIp("10.166.47.100");
        ipDo2.setEndIp("10.166.47.200");
        ipList.add(ipDo2);
        //第三行ip段
        IpDo ipDo3 = new IpDo();
        ipDo3.setBeginIp("10.166.37.150");
        ipDo3.setEndIp("10.166.37.255");
        ipList.add(ipDo3);
       
        // 校验:ip格式
        if (!validatorIpFormat(ipList))
        {
            return;
        }
        // 校验:开始ip小于等于结束ip
        if (!validatorStartIpLessThanEndIp(ipList))
        {
            return;
        }
       
        // 校验:判断IP段是否存在交集或包含关系 下标0 true or false 下标1 存在IP交集的对象
        Object[] valResult = isHaveIntersection(ipList);
        boolean flag = "true".equals(valResult[0].toString());
        if (flag)
        {
            String intersectionStr = (String)valResult[1];
            System.out.println("以下ip段存在交集,行号为: " + intersectionStr);
            return;
        }
       
    }
   
    /**
     * 校验:ip格式
     */
    public static boolean validatorIpFormat(List<IpDo> ipList)
    {
        int size = ipList.size();
        for (int i = 0; i < size; i++)
        {
            String pattern = "([1-9]|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3}";
            Matcher startMat = Pattern.compile(pattern).matcher(ipList.get(i)
                    .getBeginIp());
            Matcher endMat = Pattern.compile(pattern).matcher(ipList.get(i)
                    .getEndIp());
            if (!startMat.matches() || !endMat.matches())
            {
               
                int n = i + 1;
                System.out.println("第" + n + "行 ip格式不合法");
                return false;
            }
        }
        return true;
    }
   
    /**
     * 校验:开始ip小于等于结束ip
     */
    public static boolean validatorStartIpLessThanEndIp(List<IpDo> ipList)
    {
        boolean tag = true;
        int i = 0;
        try
        {
            int size = ipList.size();
            // 校验ip,后者>=前者
            for (i = 0; i < size; i++)
            {
                if (isLarger(ipList.get(i).getEndIp(), ipList.get(i)
                        .getBeginIp()))
                {
                    int n = i + 1;
                    System.out.println("第" + n + "行 ip结束段应该大于开始段");
                    tag = false;
                    break;
                }
            }
        }
        catch (NumberFormatException e)
        {
            tag = false;
            int n = i + 1;
            System.out.println("第" + n + "行 ip转化异常");
        }
        return tag;
    }
   
    /**
     * 判断 ip2 是否大于 ip1,若大于返回true,否则返回false
     * @param ip1 ip1
     * @param ip2 ip2
     * @return boolean boolean
     */
    public static boolean isLarger(String ip1, String ip2)
        throws NumberFormatException
    {
        boolean flag = false;
        String[] startips = ip1.split("\.");
        String[] endIps = ip2.split("\.");
        for (int i = 0; i < startips.length; i++)
        {
            if (Integer.parseInt(endIps[i]) > Integer.parseInt(startips[i]))
            {
                flag = true;
                break;
            }
            else
            {
                if (Integer.parseInt(endIps[i]) == Integer.parseInt(startips[i]))
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
        }
        return flag;
    }
   
    /**
     * 判断提交的区域配置中,是否有存在IP段有交集的区域
     * @return 下标0 true or false 下标1 存在IP交集的对象
     */
    private static Object[] isHaveIntersection(List<IpDo> ipList)
    {
        //下标0 true or false 下标1 存在IP交集的Map对象
        Object[] obj = new Object[2];
        //默认不存在交集
        obj[0] = false;
       
        //存在交集的区域名字符串,用于界面提醒
        StringBuffer buf = new StringBuffer();
        int size = ipList.size();
        for (int i = 0; i < size - 1; i++)
        {
            IpDo temp = ipList.get(i);
            for (int j = i + 1; j < size; j++)
            {
               
                IpDo tempj = ipList.get(j);
                if (isBetweenIpSeg(temp.getBeginIp(), tempj, ".")
                        || isBetweenIpSeg(tempj.getBeginIp(), temp, "."))
                {
                    obj[0] = true;
                   
                    buf.append(i + 1);
                    buf.append('-');
                    buf.append(j + 1);
                    buf.append(',');
                }
            }
        }
       
        if (buf.length() > 0)
        {
            buf = buf.deleteCharAt(buf.length() - 1);
        }
        obj[1] = buf.toString();
        return obj;
    }
   
    /**
     * 判断IP是否在IP段内
     * @param strIp 需判断的IP
     * @param regionConfigDo IP段
     * @param ipType ipv4:'.'分割  ipv6:':'分割
     * @return 在段内'true'  不在段内'false'
     */
    private static boolean isBetweenIpSeg(String strIp, IpDo ipDo, String ipType)
    {
        if (null == ipType)
        {
            return true;
        }
        long ipNumber = parseIpToNumber(strIp);
        long startIpNumber = parseIpToNumber(ipDo.getBeginIp());
        long endIpNumber = parseIpToNumber(ipDo.getEndIp());
        if (startIpNumber > ipNumber || ipNumber > endIpNumber)
        {
            //无交集
            return false;
        }
        return true;
    }
   
    /**
     * 将IPV4的IP转换成Long
     * @param ipStr Ip
     * @return IP Number
     */
    private static long parseIpToNumber(String ipStr)
    {
        /** IP进制转换值(256)*/
        final long IPHEXNUM = 256L;
        long ipNumber = 0L;
        String[] ips = ipStr.split("\.");
       
        ipNumber = ipNumber + Integer.parseInt(ips[0]) * IPHEXNUM * IPHEXNUM
                * IPHEXNUM;
        ipNumber = ipNumber + Integer.parseInt(ips[1]) * IPHEXNUM * IPHEXNUM;
        ipNumber = ipNumber + Integer.parseInt(ips[2]) * IPHEXNUM;
        ipNumber = ipNumber + Integer.parseInt(ips[3]);
       
        return ipNumber;
    }
}

原文地址:https://www.cnblogs.com/qqzy168/p/3267868.html