码迷,mamicode.com
首页 > 编程语言 > 详细

根据ip地址和子网掩码获取广播地址的java实现

时间:2015-02-09 14:12:38      阅读:690      评论:0      收藏:0      [点我收藏+]

标签:udp广播获取地址

	/**
	 * 获取广播地址
	 * */
	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;
	}

根据ip地址和子网掩码获取广播地址的java实现

标签:udp广播获取地址

原文地址:http://blog.csdn.net/xiaohu415034622/article/details/43669779

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!