前两天遇到一个业务问题,需要从不同的表中找出一批IP和一批网段的对应关系,IP格式为:xxx.xxx.xxx.xxx,网段格式为:xxx.xxx.xxx.xxx/xx。
直接上代码,判断方法如下:
* 判断该网段下是否包含该IP,子网位数包含在网段中 // * @param ip // * @param netAndMask * @return */ public static boolean isIpInSegment(String ip, String segmentStr) { try { String[] segs = segmentStr.split("/"); String ipSeg = segs[0]; String maskSeg = segs[1]; int ipInt = ipToInt(ip); int ipSegInt = ipToInt(ipSeg); int maskInt = ((1 << Integer.parseInt(maskSeg)) - 1) << (32 - Integer.parseInt(maskSeg)); return (ipInt & maskInt) == (ipSegInt & maskInt); } catch (Exception e) { return false; } } private static int ipToInt(String ip) { String[] strs = ip.split("\\."); int ipInt = 0; for (int i = 0; i < 4; i++) { ipInt = ipInt << 8 | Integer.parseInt(strs[i]); } return ipInt; }
写个main方法测试下,如下:
public static void main(String[] args) { String ipAddress = "111.0.17.52"; String addressRange = "111.0.17.0/24"; if(isIpInSegment(ipAddress,addressRange)){ System.out.println("在子网中" ); }else{ System.out.println("不在子网中" ); } }
标签:子网,网段,String,IP,xxx,segs,某个 From: https://www.cnblogs.com/ya-tao/p/17422457.html