根據子網位數獲得子網掩碼以及子網
阿新 • • 發佈:2019-02-13
近期做了一個遠端防火牆的專案,需要根據送過來的IP和子網掩碼位數計運算元網,做了最簡單的實現:
/** * 根據掩碼位數獲取子網掩碼 * * @param maskBit * @return */ public static String getMaskByBit(int maskBit) { String maskIp = ""; if (maskBit > 32 || maskBit < 1) return maskIp; String maskBinary = ""; for (int i = 0; i < 32; i++) { if (i < maskBit) maskBinary += "1"; else { maskBinary += "0"; } } for (int i = 0; i < 4; i++) { maskIp += "." + (Integer.parseInt(maskBinary.substring(8 * i, 8 * (i + 1)), 2)); } return maskIp.replaceFirst(".", ""); } /** * * @Title: getNetSegmentByIp * @Description: 根據IP計算出子網 * @param: @param * ip * @param: @return * 子網 * @return: String * @throws null */ public static String getNetSegmentByIp(String ip) { String[] ip_mask = ip.split("/"); String[] ipv4 = ip_mask[0].split("\\."); int netBit = Integer.parseInt(ip_mask[1]); String mask = getMaskByBit(netBit); String[] maskv4 = mask.split("\\."); String result = ""; for (int i = 0; i < maskv4.length; i++) { int ipBit = Integer.parseInt(ipv4[i]); int maskBit = Integer.parseInt(maskv4[i]); result += "." + (ipBit & maskBit); } return result.replaceFirst(".", "") + "/" + netBit; }
使用時,直接 getNetSegmentByIp("10.1.121.12/16")即可