androidip-address

How to get IP address of the device from code?


Is it possible to get the IP address of the device using some code?


Solution

  • With permission ACCESS_WIFI_STATE declared in AndroidManifest.xml:

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

    One can use the WifiManager to obtain the IP address:

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