通过Java实现IPv6地址简写和全写互相转换方法
2021-04-25 11:29
标签:short rgs for util import ati out bst 转换方法 IPv6地址简写和全写的一种转换方法,入参IPv6地址合法性不做校验。只对合法的IPv6地址进行简写、非简写的转换 通过Java实现IPv6地址简写和全写互相转换方法 标签:short rgs for util import ati out bst 转换方法 原文地址:https://www.cnblogs.com/luckjinyan/p/13258318.htmlpackage com.test;
import com.sun.deploy.util.StringUtils;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class transIPv6{
public static String getFullIPv6(String ipv6){
//入参为::时,此时全为0
if (ipv6.equals("::")){
return "0000:0000:0000:0000:0000:0000:0000:0000";
}
//入参已::结尾时,直接在后缀加0
if (ipv6.endsWith("::")) {
ipv6 += "0";
}
String[] arrs=ipv6.split(":");
String symbol="::";
int arrleng=arrs.length;
System.out.println(arrleng);
while (arrleng){
symbol+=":";
arrleng++;
}
ipv6=ipv6.replace("::",symbol);
System.out.println("ipv6:"+ipv6);
String fullip="";
for (String ip:ipv6.split(":")){
while (ip.length()){
ip="0"+ip;
}
fullip+=ip+‘:‘;
}
return fullip.substring(0,fullip.length()-1);
}
public static String getShortIPv6(String ipv6){
String shortIP="";
ipv6=getFullIPv6(ipv6);
String[] arr = ipv6.split(":");
//去掉每组数据前的0
for (int i = 0; i ){
arr[i] = arr[i].replaceAll("^0{1,3}", "");
}
//最长的连续0
String[] arr2 = arr.clone();
for (int i = 0; i ){
if (!"0".equals(arr2[i])){
arr2[i] = "-";
}
}
Pattern pattern = Pattern.compile("0{2,}");
Matcher matcher = pattern.matcher(StringUtils.join(Arrays.asList(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();
}
}
// 组合IPv6简写地址
if(maxStr.length()>0) {
for (int i = start; i ){
arr[i] = ":";
}
}
shortIP = StringUtils.join(Arrays.asList(arr), ":");
shortIP= shortIP.replaceAll(":{2,}", "::");
return shortIP;
}
public static void main(String[] args) {
String ipv6="1::1";
System.out.println(getFullIPv6(ipv6));
// System.out.println(getShorIPv6(ipv6));
}
}
文章标题:通过Java实现IPv6地址简写和全写互相转换方法
文章链接:http://soscw.com/index.php/essay/79373.html