zoukankan      html  css  js  c++  java
  • 点分十进制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();
        }
  • 相关阅读:
    IDEA常用快捷键(常用)
    mysql命令
    mysql localhost能连上ip连不上
    Spring Boot2部署jar包
    host localhost is not allowed ... 1130错误
    纯真ip数据库
    微软Windows XP 正版验证通知去除的工具以及手工清除办法
    周一好困哦!!!
    SQL 连接字符串的说明(转)
    IP地址和数字之间转化的算法
  • 原文地址:https://www.cnblogs.com/zengjfgit/p/5462828.html
Copyright © 2011-2022 走看看