public class IPUtils { /*** * 校验IP段是否一致 * IP段的前三部分必须一直, 比如222.72.45.0-222.72.45.255, 不能是222.72.45.0 - 110.72.45.255 * @param startSection * @param endSection * @return */ public static boolean verifyIPSectionMeet(String startSection, String endSection){ boolean startIpMeet = verifyIPMeet(startSection); if (!startIpMeet){ throw new YDIllegalArgumentException("开始段IP不合法。"); } boolean endIpMeet = verifyIPMeet(endSection); if (!endIpMeet){ throw new YDIllegalArgumentException("结束段IP不合法。"); } if (startIpMeet && endIpMeet){ String startIpPrefix = startSection.substring(0, startSection.lastIndexOf(".") + 1); String endIpPrefix = endSection.substring(0, startSection.lastIndexOf(".") + 1); if (startIpPrefix.equals(endIpPrefix)){ return true; } } return false; } /*** * 校验IP是否合法 * @param ip * @return */ public static boolean verifyIPMeet(String ip){ YDAssert.isNotNull(ip, "IP不能为空。"); // 定义正则表达式 String regex = "^(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)$"; // 判断ip地址是否与正则表达式匹配 if (ip.matches(regex)) { // 返回判断信息 return true; } return false; }}