点分十进制IP校验、转换,掩码校验

/*****************************************************************************
 *                      点分十进制IP校验、转换,掩码校验
 * 声明:
 *     本文主要记录如何对IP、掩码进行转换、校验等相关内容,注意大小端的问题。
 *
 *                                           2016-5-5 深圳 南山平山村 曾剑锋
 ****************************************************************************/

一、参考文档:
    1. java编程,如何检查一个给定的字符串IP是否合法?
        http://www.oschina.net/question/994728_115374
    2. js验证IP及子网掩码的合法性有效性示例
        http://www.bkjia.com/Javascript/763031.html

二、点分十进制IP转整形
    static public int numericIPToInt(String numericIP) {
        String [] ips = numericIP.split("\.");
        int ip = Integer.valueOf(ips[0]) << 24 | 
            Integer.valueOf(ips[1]) << 16 |
            Integer.valueOf(ips[2]) << 8 |
            Integer.valueOf(ips[3]);
        
        return ip;
    }

    static public String intToNumericIP(int ip) {
        return (ip & 0xff) + "." 
            + ((ip >> 8) & 0xff) + "." 
            + ((ip >> 16) & 0xff)+ "." 
            + ((ip >> 24) & 0xff));
    }

三、IP校验
    public static boolean isIpv4(String ipAddress) {
        String ip = "^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\."
                + "(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\."
                + "(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\."
                + "(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$";
        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }

四、netmask校验
    public static boolean isNetmask(String netmask) {
        String mask="^(254|252|248|240|224|192|128|0)\.0\.0\.0" +
                "|255\.(254|252|248|240|224|192|128|0)\.0\.0" +
                "|255\.255\.(254|252|248|240|224|192|128|0)\.0" +
                "|255\.255\.255\.(254|252|248|240|224|192|128|0)$"; 
        Pattern pattern = Pattern.compile(mask);
        Matcher matcher = pattern.matcher(netmask);
        return matcher.matches();
    }
原文地址:https://www.cnblogs.com/zengjfgit/p/5462828.html