If you want to get the broadcast IP address from a wifi access point you must first request a wifi multicast lock on the device. Android by default filters out UDP broadcast packets.
Follow these steps:
1. first add the following to your android Manifest.xml file:
2. Second copy this method into your activity or service class:
public void getMultiCastLock() {
WifiManager wim= (WifiManager) _androidContext.getSystemService(Context.WIFI_SERVICE);
/* Turn off multicast filter */
_mcastLock = wim.createMulticastLock(Context.WIFI_SERVICE);
if(!_mcastLock.isHeld()){
_mcastLock.acquire();
}
}
*NOTE:replace _androidContext with your local context object;
3. Copy this method and call it after you acquire the lock
public String getBroadcastAddress() {
InetAddress currentInetAddress = null;
String returnValue = "";
WifiManager myWifiManager = (WifiManager) _androidContext.getSystemService(Context.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);
try {
currentInetAddress= InetAddress.getByAddress(quads);
} catch (Exception e) {
}
if(currentInetAddress != null){
returnValue = currentInetAddress.toString().substring(1);
}
return returnValue;
}
4. After you are finished. You must release the lock.
No comments:
Post a Comment