以下代码已经过工业级效验,已满足我厂应用的需要。如有问题,可于我留言,谢谢。
代码块
/** * 将ipv4转为32 bit. 返回结果cidr的二个部分 * * @param ip * @return * @throws IPv4Exception */ public static int[] convert2Bit32(String ip) throws IPv4Exception { int[] result = { 0, NULL_NET }; String[] cidr = ip.split("\\/" , -1); if (cidr.length > 2 || cidr.length == 0) { throw new IPv4Exception("Invalid IPv4 " + ip); } else if (cidr.length == 2) { if (!isPositive(cidr[1])) { throw new IPv4Exception("Invalid IPv4 " + ip); } result[1] = Integer.parseInt(cidr[1]); if (result[1] < 0 || result[1] > 32) { throw new IPv4Exception("Invalid IPv4 " + ip); } else if (result[1] == 0 && !"0.0.0.0".equals(cidr[0])) { throw new IPv4Exception("Invalid IPv4 " + ip); } } String[] addr = cidr[0].split("\\." , -1); if (addr.length != 4) { throw new IPv4Exception("Invalid IPv4 " + ip); } for (String f : addr) { if (!isPositive(f)) { throw new IPv4Exception("Invalid IPv4 " + ip); } int n = Integer.parseInt(f); if (n < 0 || n > 255) { throw new IPv4Exception("Invalid IPv4 " + ip); } result[0] = (result[0] << 8) | n; } return result; private static boolean isPositive(String val) { if (val == null || val.length() == 0) { return false; } int n = val.length(); if (n == 0 || n > 3) { //此处可以不加限制,即127.0.0.00001也是正确ip return false; } for (int i = 0; i < n; i++) { if (!Character.isDigit(val.charAt(i))) { return false; } } return true; } }
注意:
- 效验方法 :请调用convert2Bit32方法完成效验
- split :使用split(String regex,int limit),将limit设置为-1,来防止split将分割后的字符串结尾空字符串丢弃。这样就消除了出现将“127.0.0.1.”效验为正确的bug。
同时效验ipv4和cidr ip的方法
最新推荐文章于 2024-06-04 14:16:40 发布