关于子网掩码的几个代码
1、验证是否是子网掩码
public static boolean isMask(String mask){// Pattern pattern = Pattern.compile("(254|252|248|240|224|192|128|0)\\.0\\.0\\.0|255\\.(254|252|248|240|224|192|128|0)\\.0\\.0|255\\.255\\.(254|252|248|240|224|192|128|0)\\.0|255\\.255\\.255\\.(255|254|252|248|240|224|192|128|0)|^[1-9]$|^2\\d$|^3[0-2]$");Pattern pattern = Pattern.compile("(^((\\d|[01]?\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[01]?\\d\\d|2[0-4]\\d|25[0-5])$)|^(\\d|[1-2]\\d|3[0-2])$");return pattern.matcher(mask).matches();}
2、将ip或者数字类型子网掩码统一转换为255.255.255.0类型ip类型的子网掩码
//将子网掩码转换成ip子网掩码形式,比如输入"255.255.255.255" 或者32统一输出为255.255.255.255public static String mask2ipMask(String mask) {String ipMask = null;/* // 如果不是子网掩码if (!isMask(mask)) {System.out.println("ip掩码格式(" + mask + ")不正确");logger.error("ip掩码格式(" + mask + ")不正确");}else*/// 如果是ip类型的子网掩码[0.0.0.0,255.255.255.255]则直接返回if (mask.contains(".")) {ipMask = mask;// 如果是数字类型的子网掩码[0,32]} else {int inetMask = Integer.valueOf(mask);int part = inetMask / 8;int remainder = inetMask % 8;int sum = 0;for (int i = 8; i > 8 - remainder; i--) {sum = sum + (int) Math.pow(2, i - 1);}if (part == 0) {ipMask = sum + ".0.0.0";} else if (part == 1) {ipMask = "255." + sum + ".0.0";} else if (part == 2) {ipMask = "255.255." + sum + ".0";} else if (part == 3) {ipMask = "255.255.255." + sum;} else if (part == 4) {ipMask = "255.255.255.255";}}return ipMask;}
3、将ip类型的子网掩码转换成数字
public static int maskStr2InetMask(String maskStr){
StringBuffer sb ;
String str;
int inetmask = 0;
int count = 0;
String[] ipSegment = maskStr.split("\\.");
for(int n =0; n<ipSegment.length;n++){
sb = toBin(Integer.parseInt(ipSegment[n]));
str = sb.reverse().toString();
count=0;
for(int i=0; i<str.length();i++){
i=str.indexOf("1",i);
if(i==-1){
break;
}
count++;
}
inetmask+=count;
}
return inetmask;
}
本文介绍了三种子网掩码转换方法:验证子网掩码有效性、数字型转IP型子网掩码及IP型转数字型子网掩码。通过这些方法可以轻松实现不同格式间的转换。
679

被折叠的 条评论
为什么被折叠?



