首页 > 代码库 > Android UDP广播包抓取
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广播包抓取
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。