Wednesday, September 22, 2010

Get IP address of device in android

AIM :Get IP address of device in android
Solution: 

The following method returns the device ip address which is currently used by device irrespective of type of connection ie.,either 3g/wifi/any other.

It returns NULL if there is no network connection.


public static String getipAddress() {
            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()) {
                            String ipaddress=inetAddress.getHostAddress().toString();
                            Log.e("ip address",""+ipaddress);
                            return ipaddress;
                        }
                    }
                }
            } catch (SocketException ex) {
                Log.e("Socket exception in GetIP Address of Utilities", ex.toString());
            }
            return null;
    }

Call the above method wherever you wnat to get ip address as
String ipaddress=getipAddress();

--------------------------

Android Developers Blog

Ram's shared items