点分十进制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();
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值