Tuesday, March 20, 2012

How to get IP address of Android Device?


The obvious way to get the IP-Address of your device simply doesn’t work on Android.
The first thing I tried was using the WifiInfo.

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();

But wait: ipAddress is an integer? Of course not. I also did the math but couldn’t find a way to get the IP out of this integer. So thats not the right way.

Another possibility I found was to create a socket connection and use the Socket instance to get the local ip address.

try {
Socket socket = new Socket("www.droidnova.com", 80);
Log.i("", socket.getLocalAddress().toString());
} catch (Exception e) {
Log.i("", e.getMessage());
}

The disadvantages should be clear:
  • You generate traffic – may result in costs for the user
  • Your program depend on the Server you create a socket connection to
  • The same exceptions may be thrown for different reasons – bad if you want to display a message to tell the user what he should do to fix the problem
The right thing is to iterate over all network interfaces and iterate there over all ip addresses.

public String getLocalIpAddress() {
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()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}


So if this method returns null, there is no connection available.
If the method returns a string, this string contains the ip address currently used by the device independent of 3G or WiFi.

No comments:

Post a Comment