/** * 转换为简写 * * @param IPv6Str * @return */ public static String parseFullIPv6ToAbbreviation(String IPv6Str) { String fullIPv6 = ""; if (IPv6Str.length() - IPv6Str.replaceAll(":", "").length() != 7) { String[] ss = IPv6Str.split(":"); StringBuilder ipStr = new StringBuilder(39); for (int i = 0, len = ss.length; i < len; i++) { if (ss[i].length() != 4) { if (StringUtil.isEmpty(ss[i])) { ipStr.append("0000:"); } else { ipStr.append(String.format("%04d", Integer.parseInt(ss[i]))).append(":"); } } else { ipStr.append(ss[i]).append(":"); } } fullIPv6 = ipStr.toString().substring(0,ipStr.toString().length()-1); } String[] arr = fullIPv6.split(":"); for (int i = 0, len = arr.length; i < len; i++) { arr[i] = arr[i].replaceAll("^0{1,3}", ""); } String[] arr2 = arr.clone(); for (int i = 0, len = arr2.length; i < len; i++) { if (!"0".equals(arr2[i])) { arr2[i] = "-"; } } //找到最长的连续的0 Pattern pattern = Pattern.compile("0{2,}"); Matcher matcher = pattern.matcher(StringUtils.join(arr2, "")); String maxStr = ""; int start = -1; int end = -1; while (matcher.find()) { if (maxStr.length() < matcher.group().length()) { maxStr = matcher.group(); start = matcher.start(); end = matcher.end(); } } //合并 if (maxStr.length() > 0) { for (int i = start; i < end; i++) { arr[i] = ":"; } } return StringUtils.join(arr, ":").replaceAll(":{2,}", "::"); }
/** * 简写的IPv6 转换成 非简写的IPv6 * * @param simpleIPv6 * @return fullIPv6 */ public static String parseAbbreviationToFullIPv6(String simpleIPv6) { if ("::".equals(simpleIPv6)) { return "0000:0000:0000:0000:0000:0000:0000:0000"; } String[] arr = new String[]{"0000", "0000", "0000", "0000", "0000", "0000", "0000", "0000"}; if (simpleIPv6.startsWith("::")) { String[] tempArr = simpleIPv6.substring(2).split(":"); for (int i = 0; i < tempArr.length; i++) { arr[i + 8 - tempArr.length] = String.format("%04d", Integer.parseInt(tempArr[i])); } } else if (simpleIPv6.endsWith("::")) { String[] tempArr = simpleIPv6.substring(0, simpleIPv6.length() - 2).split(":"); for (int i = 0; i < tempArr.length; i++) { arr[i] = String.format("%04d", Integer.parseInt(tempArr[i])); } } else if (simpleIPv6.contains("::")) { String[] tempArr = simpleIPv6.split("::"); String[] tempArr0 = tempArr[0].split(":"); for (int i = 0; i < tempArr0.length; i++) { arr[i] = String.format("%04d", Integer.parseInt(tempArr0[i])); } String[] temp1 = tempArr[1].split(":"); for (int i = 0; i < temp1.length; i++) { arr[i + 8 - temp1.length] = String.format("%04d", Integer.parseInt(temp1[i])); } } else { String[] tempArr = simpleIPv6.split(":"); for (int i = 0; i < tempArr.length; i++) { arr[i] = String.format("%04d", Integer.parseInt(tempArr[i])); } } return StringUtils.join(arr, ":"); }