Wednesday, November 10, 2010

Obtain IP Address for android device

Two ways to find the device ip:-

1. Method1:-  Open a socket to a known website/webserver like google.com or yahoo.com and get the ip using the technique shown below. It is straight forward(but not recommended)
String get_ip(){
java.net.Socket conn = null;
String ipAddress;

try {
conn = new java.net.Socket("www.google.com", 80);
} catch (UnknownHostException unknownhostexception) {
unknownhostexception.printStackTrace();
} catch (IOException ioexception) {
ioexception.printStackTrace();

ipAddress = conn.getLocalAddress().toString();
Toast.makeText(ip.this," Device IP --"+ipAddress,Toast.LENGTH_LONG).show();
return ipAddress;
}
2. Method2:- Iterate over all network interfaces and iterate there over all ip addresses. (Recommended way)

public String getLocalIpAddress() {

try {
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses();
enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();}}}
} catch (SocketException exception) {
Log.e("We got Exception here", exception.toString());
}
return null;
}

Note:- This will give you simple way to get the ip address (For device on WiFi we need to access wifiManager class) and is independent of Android. This is generic java code and can be used on the laptop as well


Hope it helps!