/** * 获取广播地址 * */ public static String getBroadcastAddress(String subnet, String ip) { String[] ips = ip.split("\\."); String[] subnets = subnet.split("\\."); StringBuffer sb = new StringBuffer(); for (int i = 0; i < ips.length; i++) { ips[i] = String.valueOf((~Integer.parseInt(subnets[i])) | (Integer.parseInt(ips[i]))); sb.append(turnToStr(Integer.parseInt(ips[i]))); if (i != (ips.length - 1)) sb.append("."); } return turnToIp(sb.toString()); } private static String turnToStr(int num) { String str = ""; str = Integer.toBinaryString(num); int len = 8 - str.length(); for (int i = 0; i < len; i++) { str = "0" + str; } if (len < 0) str = str.substring(24, 32); return str; } /** * 转换成Str * */ private static String turnToIp(String str) { String[] ips = str.split("\\."); StringBuffer sb = new StringBuffer(); for (int i = 0; i < ips.length; i++) { sb.append(turnToInt(ips[i])); sb.append("."); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } /** * 转换成int * */ private static int turnToInt(String str) { int total = 0; int top = str.length(); for (int i = 0; i < str.length(); i++) { String h = String.valueOf(str.charAt(i)); top--; total += ((int) Math.pow(2, top)) * (Integer.parseInt(h)); } return total; }
时间: 2024-10-07 23:47:44