Reputation: 2304
In my app I want to broadcast some UDP packets. I'm currently using this methode to get the required broadcast address:
InetAddress getBroadcastAddress() throws IOException {
WifiManager wifi = mContext.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
// handle null somehow
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);
}
-> https://code.google.com/p/boxeeremote/wiki/AndroidUDP
That works fine, but if the devices has activated a hotspot and tries to broadcast a packet following SocketException is thrown: SocketException: sendto failed: ENETUNREACH (Network is unreachable)
How can I get the right broadcast-address on a device which is "providing" a hotspot?
All unicast addresses I tried yet worked fine...
thx & regards
PS: minimum SDK is API 8 !
Upvotes: 2
Views: 4462
Reputation: 2304
I managed the problem using this code:
private InetAddress getBroadcastAddress(WifiManager wm, int ipAddress) throws IOException {
DhcpInfo dhcp = wm.getDhcpInfo();
if(dhcp == null)
return InetAddress.getByName("255.255.255.255");
int broadcast = (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);
}
Important is that you call getBroadcastAddress with the "real" ip-address (some methods I've seen can't provide that on a hotspot):
public static int getCodecIpAddress(WifiManager wm, NetworkInfo wifi){
WifiInfo wi = wm.getConnectionInfo();
if(wifi.isConnected())
return wi.getIpAddress(); //normal wifi
Method method = null;
try {
method = wm.getClass().getDeclaredMethod("getWifiApState");
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(method != null)
method.setAccessible(true);
int actualState = -1;
try {
if(method!=null)
actualState = (Integer) method.invoke(wm, (Object[]) null);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
if(actualState==13){ //if wifiAP is enabled
return "192.168.43.1" //hardcoded WifiAP ip
}
return 0;
}
public static int convertIP2Int(byte[] ipAddress){
return (int) (Math.pow(256, 3)*Integer.valueOf(ipAddress[3] & 0xFF)+Math.pow(256, 2)*Integer.valueOf(ipAddress[2] & 0xFF)+256*Integer.valueOf(ipAddress[1] & 0xFF)+Integer.valueOf(ipAddress[0] & 0xFF));
}
Upvotes: 5