[Android]获取局域网广播地址的两种方法

[Android]获取局域网广播地址的两种方法

第一种是自己写的,有一些bug,不过凑合着用也可以,第二种是stackoverflow的,推荐用这种。

(1)

private InetAddress calcBroadcastAddress(InetAddress mask, InetAddress ip)
			throws IOException {
		int ipaddress = getIntAddress(ip);
		int maskaddress = getIntAddress(mask);
		int broadcast = ipaddress & maskaddress | ~maskaddress;
		byte[] quads = new byte[4];
		for (int k = 0; k < 4; k++) {
			quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
		}
		return InetAddress.getByAddress(quads);
	}

	private InetAddress getBroadcastAddress() throws IOException {
		// 自动获取
		String strIp = getCommandResult("/system/bin/getprop",
				"dhcp.eth0.ipaddress");
		String strMask = getCommandResult("/system/bin/getprop",
				"dhcp.eth0.mask");
		if (!strIp.equals("\n")) {
			InetAddress mask = InetAddress.getByName(strMask);
			InetAddress ip = InetAddress.getByName(strIp);
			Log.v("ws-discovery", "auto ip:" + strIp);
			return calcBroadcastAddress(mask, ip);

		} else {
			// 手动配置
			String strManual = getCommandResult("/system/bin/ifconfig", "eth0");
			String[] netInfo = strManual.split(" ");
			if (netInfo.length >= 5) {
				InetAddress mask = InetAddress.getByName(netInfo[4]);
				InetAddress ip = InetAddress.getByName(netInfo[2]);
				Log.v("ws-discovery", "manual ip:" + netInfo[2]);
				return calcBroadcastAddress(mask, ip);
			}
		}
		// wifi
		WifiManager wifi = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		DhcpInfo dhcp = wifi.getDhcpInfo();
		Log.v("ws-discovery", "wifi ip:" + Integer.toString(dhcp.ipAddress));
		int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
		byte[] quads = new byte[4];
		for (int k = 0; k < 4; k++) {
			quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
		}
		return InetAddress.getByAddress(quads);
	}
private int getIntAddress(InetAddress address) {
		byte[] addrs = address.getAddress();
		int addr = 0;
		addr = ((addrs[3] & 0xff) << 24) | ((addrs[2] & 0xff) << 16)
				| ((addrs[1] & 0xff) << 8) | (addrs[0] & 0xff);
		return addr;
	}

	private String getCommandResult(String commands, String args) {
		Process process = null;
		String inet = null;
		try {
			process = new ProcessBuilder().command(commands, args)
					.redirectErrorStream(true).start();
			InputStream in = process.getInputStream();
			int count = 0;
			while (count == 0) {
				count = in.available();
			}
			byte[] b = new byte[count];
			in.read(b);
			inet = new String(b);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (process != null)
				process.destroy();
		}
		return inet;
	}


(2)

public static String getBroadcast() throws SocketException {
	    System.setProperty("java.net.preferIPv4Stack", "true");
	    for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum.hasMoreElements();) {
	        NetworkInterface ni = niEnum.nextElement();
	        if (!ni.isLoopback()) {
	            for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
	            	if (interfaceAddress.getBroadcast() != null) {
	            		return interfaceAddress.getBroadcast().toString().substring(1);
					}
	            }
	        }
	    }
	    return null;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值