Get Device IP Address Code Snippet in Android Studio

 

Welcome. In this tutorial you will learn how to get our Device’s IP address in any Android Phone or Tablet.

Example to get IP Address in Android Studio

You might have seen that in many android applications our IP Address is shown automatically. Many VPN apps use this feature to tell their users that their IP is not secured. If you also want to use this feature in your android application then you will have to just use the code snippet given below:-

For this purpose we will have to use the WifiManager class which will allow us to manage all wifi connectivity related settings.  The WIFI_SERVICE is used with getSystemService to retrive a wifimanager for handling management of wifi access. The function getConnectionInfo() is also used to return dynamic information about the current Wi-Fi connection, but only if there is any active connection. We have also used Formatter tool here to format the received data from wifiManager and extract our desired IP address.

The above code stated here will get the current IP address and will display it as a text in the text view. You can use this code as required in any part of your Android app.

Also note that the above code will require Internet so you will have to first modify the AndroidManifests file and add the following code to it.

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

 

The image below shows an example where the IP address of my current device was shown.

Get IP Address Code for Android Studio Example

The Complete Code Snippet for above example is given below:-

Java (MainActivity.java)

 

XML (activity_main.xml)

 

 

 

You can directly copy paste these snippets to your android studio, and they should work perfectly. Just save and run your project.

For a more detailed guide, you can also visit android’s official guide below:-

https://developer.android.com/reference/android/net/wifi/WifiManager

Comment down below if you are facing any problems.

 

Also Read:-

Leave a Reply

Your email address will not be published. Required fields are marked *