我这边想要在Android端获取都目前同一个局域网的设备并且获取到其他设备的IP,
一直没有找到好的方法,不知道各位大神有没有什么好的方法,小弟在这里非常感谢。
3条回答 默认 最新
- 战在春秋 2017-03-21 14:15关注
附上一段代码,亲测可用。
static class NetworkSniffTask extends AsyncTask<Void, Void, Void> { private static final String TAG = Constants.TAG + "nstask"; private WeakReference<Context> mContextRef; public NetworkSniffTask(Context context) { mContextRef = new WeakReference<Context>(context); } @Override protected Void doInBackground(Void... voids) { Log.d(TAG, "Let's sniff the network"); try { Context context = mContextRef.get(); if (context != null) { ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); WifiManager wm = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); WifiInfo connectionInfo = wm.getConnectionInfo(); int ipAddress = connectionInfo.getIpAddress(); String ipString = Formatter.formatIpAddress(ipAddress); Log.d(TAG, "activeNetwork: " + String.valueOf(activeNetwork)); Log.d(TAG, "ipString: " + String.valueOf(ipString)); String prefix = ipString.substring(0, ipString.lastIndexOf(".") + 1); Log.d(TAG, "prefix: " + prefix); for (int i = 0; i < 255; i++) { String testIp = prefix + String.valueOf(i); InetAddress address = InetAddress.getByName(testIp); boolean reachable = address.isReachable(1000); String hostName = address.getCanonicalHostName(); if (reachable) Log.i(TAG, "Host: " + String.valueOf(hostName) + "(" + String.valueOf(testIp) + ") is reachable!"); } } } catch (Throwable t) { Log.e(TAG, "Well that's not good.", t); } return null; }
另外还需要加入以下权限:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 2无用 1