how to find ip address of wifi connected devices in android

Viewed 30

I tried to get IP address of wifi connected devices in android. But I couldn't get those. If anyone has rich experience in this, can you help me? Hope to explain with results in details.

public void findAdressConnectedWifi() {
        try {
            WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            int ip = wifiInfo.getIpAddress();
            String ipAddress = Formatter.formatIpAddress(ip);

            Toast.makeText(this, ipAddress, Toast.LENGTH_LONG).show();

            String prefix = ipAddress.substring(0, ipAddress.lastIndexOf(".") + 1);
            Log.d("wifi => ", "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) {
                    MainActivity.this.ipAddressArray.add(testIp);
                    Log.i("wifi => ", "Host: " + String.valueOf(hostName) + "(" + String.valueOf(testIp) + ") is reachable!");
                    Toast.makeText(this, "Host: " + String.valueOf(hostName) + "(" + String.valueOf(testIp) + ") is reachable!", Toast.LENGTH_LONG).show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
1 Answers

You need to add permission ACCESS_WIFI_STATE in AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Then you can use below code

Context context = requireContext().getApplicationContext();
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
Related