ANDROID获取网络上的所有IP地址

时间:2016-06-30 10:19:10

标签: java android listview android-studio networking

我想找到我网络上的所有IP地址。

例如,我有按钮和列表视图的活动。

当我点击按钮时,我会在netowrk上获取所有IP地址并将其放入列表视图中。

抱歉我的英文=)

1 个答案:

答案 0 :(得分:3)

试试这个:

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;
    }
}