簡體   English   中英

Android在啟用熱點的設備上發送UDP廣播

[英]Android sending UDP broadcast on a hotspot enabling device

在我的應用中,我想廣播一些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);
}  

-> https://code.google.com/p/boxeeremote/wiki/AndroidUDP

效果很好,但是如果設備已激活熱點並嘗試在引發SocketException: sendto failed: ENETUNREACH (Network is unreachable)之后廣播數據包: SocketException: sendto failed: ENETUNREACH (Network is unreachable)
如何在“提供”熱點的設備上獲得正確的廣播地址? 我嘗試過的所有單播地址都運行良好...

問候與問候

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

重要的是,您使用“真實的” ip地址調用getBroadcastAddress(我見過的某些方法無法在熱點上提供該地址):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM