您的当前位置:首页正文

Java正则表达式判断内网ip

2024-11-09 来源:个人技术集锦

局域网ip一般为:

10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255

下面这段代码判断ip或url 是否存在这三个网段的匹配。

public static boolean innerIP(String ip) {

        //匹配10.0.0.0 - 10.255.255.255的网段
        String pattern_10 = "^(\\D)*10(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){3}";

        //匹配172.16.0.0 - 172.31.255.255的网段
        String pattern_172 = "172\\.([1][6-9]|[2]\\d|3[01])(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){2}";

        //匹配192.168.0.0 - 192.168.255.255的网段
        String pattern_192 = "192\\.168(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){2}";

        //合起来写
        String pattern = "((192\\.168|172\\.([1][6-9]|[2]\\d|3[01]))"
                + "(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){2}|"
                + "^(\\D)*10(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){3})";

        Pattern reg = Pattern.compile(pattern);
        Matcher match = reg.matcher(ip);

        return match.find();

    }
Top