Java关于数值类型的子网掩码和ip类型的子网掩码相互转换

关于子网掩码的几个代码



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.255

	public 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值