zoukankan      html  css  js  c++  java
  • 关于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

  • 相关阅读:
    条件注释,判断浏览器版本
    IE 兼容模式下不支持DIV CSS样式display:inline-block,解决
    Hibernate配置问题
    初学Hibernate
    Ognl基本使用
    初学Struts2-自定义拦截器及其配置
    初学structs2,表单验证简单补充
    初学structs2,表单验证
    structs2标签简单实用,及自定义转换器示例代码
    一些专业术语的总结
  • 原文地址:https://www.cnblogs.com/TLightSky/p/4192862.html
Copyright © 2011-2022 走看看