网络上的所有IP地址

网络上的所有IP地址

我想找到我网络上的所有IP地址。
例如,我有一个按钮和一个列表视图的活动。
当我点击这个按钮时,我得到了网络上的所有IP地址,并将其放入一个列表视图中。
对不起我的英语=)

最佳答案

试试这个:

private static class NetworkSniffTask extends AsyncTask<Void, Void, Void> {
    private static final String TAG = "NetworkSniffTask";
    private WeakReference<Context> mContextRef;

    private NetworkSniffTask(Context context) {
        mContextRef = new WeakReference<>(context);
    }

    @Override
    protected Void doInBackground(Void... voids) {
        Log.e(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.e(TAG, "activeNetwork: " + String.valueOf(activeNetwork));
                Log.e(TAG, "ipString: " + String.valueOf(ipString));
                String prefix = ipString.substring(0, ipString.lastIndexOf(".") + 1);
                Log.e(TAG, "prefix: " + prefix);
                for (int i = 0; i < 255; i++) {
                    String testIp = prefix + String.valueOf(i);
                    InetAddress name = InetAddress.getByName(testIp);
                    String hostName = name.getCanonicalHostName();
                    if (name.isReachable(1000))
                        Log.e(TAG, "Host:" + hostName);
                }
            }
        } catch (Throwable t) {
            Log.e(TAG, "Well that's not good.", t);
        }
        return null;
    }
}

08-04 01:27