Get the Local IP address of your device

Have a great day.


Set the permission in Manifest.xml

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

Then just use below code:

 public String getLocalIpAddress() {
        String firstIP = "192.168.0.1";
        ArrayList<String> ipList = new ArrayList<String>();
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        Log.d(TAG, inetAddress.getHostAddress().toString());
                        ipList.add(inetAddress.getHostAddress().toString());
                        //return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(TAG, ex.toString());
        }

        int firstIP4 = -1;
        for (int i = 0; i < ipList.size(); i++) {// String s : ipList){
            if (ipList.get(i).indexOf("%") != -1) {
                //IP6 address
                ;
            } else {
                firstIP4 = i;
                Log.i("Local IP: ", ipList.get(i));
            }
        }
        if (firstIP4 != -1) {
            firstIP = ipList.get(firstIP4);
        }
        return firstIP;
    }

Comments

Popular posts from this blog

Flutter Bloc - Clean Architecture

What's new in android 14?

Dependencies vs Dev Dependencies in Flutter