qq_36373717
qq_36373717
2017-03-21 09:28
采纳率: 100%
浏览 5.7k

Android端如何获取同一局域网下的其他设备(包括pc)

我这边想要在Android端获取都目前同一个局域网的设备并且获取到其他设备的IP,
一直没有找到好的方法,不知道各位大神有没有什么好的方法,小弟在这里非常感谢。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • fight_in_dl
    战在春秋 2017-03-21 22: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 评论
  • oyljerry
    oyljerry 2017-03-21 10:23

    循环用ping的方式的,isReachable()

    点赞 评论
  • caozhy

    http://blog.csdn.net/yhcelebrite/article/details/11299595
    得到你的网段,然后从.1到.256扫描

    点赞 评论

相关推荐