關於Android熱點模式下的UDP廣播


最近嘗試讓easylink3在熱點模式下連接,發現用普通的廣播地址會報錯,Network unreachable

嘗試按照stackoverflow上的方法:

    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 convertIP2Int("192.168.43.1".getBytes()); //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));
    }

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

但是發現wm.getDhcpInfo得到的mask不對,是0

這樣最終廣播地址會是255.255.255.255

再次修正,將mask強行變為0.0.0.255之后,可以成功進行廣播

但是多播還是不行,需要繼續研究

update ----------------------

多播也ok了,參考這篇文章:https://plus.google.com/+Chainfire/posts/9NMemrKYnCd

在熱點模式下,默認的networkinterface是不對的,需要使用MulticastSocket::setNetworkInterface()來指定wlan作為多播interface

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM