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 or and get the ip using the technique shown below. It is straight forward(but not recommended)
String get_ip(){ conn = null;
String ipAddress;

try {
conn = new"", 80);
} catch (UnknownHostException unknownhostexception) {
} catch (IOException ioexception) {

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!