Android在热点启用设备上发送UDP广播

Android在热点启用设备上发送UDP广播,android,udp,wifi,broadcast,android-networking,Android,Udp,Wifi,Broadcast,Android Networking,在我的应用程序中,我想广播一些UDP数据包。我目前正在使用此方法获取所需的广播地址: InetAddress getBroadcastAddress() throws IOException { WifiManager wifi = mContext.getSystemService(Context.WIFI_SERVICE); DhcpInfo dhcp = wifi.getDhcpInfo(); // handle null somehow int broadcast = (dhcp.ip

在我的应用程序中,我想广播一些UDP数据包。我目前正在使用此方法获取所需的广播地址:

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);
}  
InetAddress getBroadcastAddress()引发IOException{
WifiManager wifi=mContext.getSystemService(Context.wifi\u服务);
DhcpInfo dhcp=wifi.getDhcpInfo();
//以某种方式处理null
int broadcast=(dhcp.ipAddress&dhcp.netmask)|~dhcp.netmask;
字节[]四元组=新字节[4];
对于(int k=0;k<4;k++)
四元组[k]=(字节)((广播>>k*8)和0xFF);
返回InetAddress.getByAddress(quads);
}  
->

这可以正常工作,但如果设备已激活热点并尝试在抛出SocketException之后广播数据包:
SocketException:sendto失败:ENETUNREACH(网络不可访问)

如何在“提供”热点的设备上获得正确的广播地址? 我尝试过的所有单播地址都很好

thx&问候


PS:最低SDK是API 8

我使用以下代码处理了这个问题:

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);
} 
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));
}