Android UDP广播包抓取

只是贴代码,以前写的突然忘记了.



    private WifiManager.MulticastLock multicastLock;

    public void init(Context context){
         WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
         multicastLock = wifiManager.createMulticastLock("my_net");
    }

    public byte[] fetchData(){
        try {
            multicastLock.acquire();
            MulticastSocket multicastSocket = new MulticastSocket(55551);
            InetAddress group = InetAddress.getByName("224.0.0.2");
            multicastSocket.setSoTimeout(3000);
            multicastSocket.joinGroup(group);
            multicastSocket.setLoopbackMode(true);
            byte[] buffer = new byte[512];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            multicastSocket.receive(packet);
            return buffer;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            multicastLock.release();//一定要释放
        }
        return null;
    }

权限加入


    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。