简体   繁体   中英

ANDROID get all ip addresses on network

I would like to find all ip addresses on my network.

For example i have activity with a button and a listview.

When i click the button, i get all ip addresses on my netowrk and put into a listview.

Sorry for my english =)

try this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM