depicus

changing the digital world one bit at a time...

Blants (noun) the rants of a blogger

Android: Getting the Broadcast Address of your Wifi connection

May 1, 2011 by The Man

If you ever need to know the broadcast address of your wifi connection…

private InetAddress getBroadcastAddress() throws IOException {
	WifiManager myWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
	DhcpInfo myDhcpInfo = myWifiManager.getDhcpInfo();
	if (myDhcpInfo == null) {
		System.out.println("Could not get broadcast address");
		return null;
	}
	int broadcast = (myDhcpInfo.ipAddress & myDhcpInfo.netmask)
				| ~myDhcpInfo.netmask;
	byte[] quads = new byte[4];
	for (int k = 0; k < 4; k++)
	quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
	return InetAddress.getByAddress(quads);
}