码迷,mamicode.com
首页 > 移动开发 > 详细

Android UDP广播包抓取

时间:2015-01-04 19:17:48      阅读:155      评论:0      收藏:0      [点我收藏+]

标签: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" />



Android UDP广播包抓取

标签:android   udp   

原文地址:http://blog.csdn.net/birdsaction/article/details/42395191

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!