Download source code of the article.
For one of my project I need to get the IP address of the device, I searched a lot and found this link.
The method is to enumerate all network interfaces and find the IP address if it is not loop-back adapter. This will give the IP address if you are connected to a network (WiFi or Cellular).
You can also use the WifiManger to get he IP address if you are connected to WiFi network. The following code retrieves the WiFi IP address:
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress();
Note that the getIpAddress returns an integer value. To convert to readable format we can use the following code:
String.format("%d.%d.%d.%d",
(ipAddress & 0xff),
(ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff),
(ipAddress >> 24 & 0xff))
Note: To use the first method you need the android.permission.INTERNET permission, otherwise it will throw unknown error. For the second method you need android.permission.ACCESS_WIFI_STATE.
There is a ready system API for formatting IP address: http://developer.android.com/reference/android/text/format/Formatter.html#formatIpAddress(int)
Thank you Alex for mentioning it.
There is a ready system API for formatting IP address: http://developer.android.com/reference/android/text/format/Formatter.html#formatIpAddress(int)
Thank you Alex for mentioning it.
There is a ready system API for formatting IP address: http://developer.android.com/reference/android/text/format/Formatter.html#formatIpAddress(int)
Thank you Alex for mentioning it.
There is a ready system API for formatting IP address: http://developer.android.com/reference/android/text/format/Formatter.html#formatIpAddress(int)
Thank you Alex for mentioning it.
Krishnaraj, your code works fine, thanks.
Alex, looks like the formatIpAddress function is depreciated and I can’t make work their suggested alternative.