15

In my android device I am trying to find its IP address(IPV4).
If I do the following code

InetAddress inet = InetAddress.getLocalHost();
System.out.println(inet.getHostAddress()); //giving me 127.0.0.1

The code is giving me 127.0.0.1.
I wanted to get the actual IP 198.168.xx.xx.

(In My pc the same code giving me the actual IP though.)

Ayush
  • 3,989
  • 1
  • 26
  • 34
Vishnudev K
  • 2,874
  • 3
  • 27
  • 42

2 Answers2

25
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()&&inetAddress instanceof Inet4Address) {
                            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; 
    }

Give permissions

Also add in mainfest.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Vishnudev K
  • 2,874
  • 3
  • 27
  • 42
Ayush
  • 3,989
  • 1
  • 26
  • 34
2

You can use this to get your IP address.

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
return String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
        (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));

This returns it as a String in the form "X.X.X.X"

The only permission you need in your manifest.xml is

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Ken Wolf
  • 23,133
  • 6
  • 63
  • 84
  • And if he is not using WiFi? – SJuan76 Jun 22 '13 at 15:05
  • What's an example of a device that doesn't use wifi to get an internal LAN address? 198.168.xx.xx. Ethernet port? – Ken Wolf Jun 22 '13 at 15:09
  • As often, I concentrate in the body of the question and miss data from the header (it is the only place where the `LAN` part is informed). And yes, an ethernet port is possible (though I agree that it is not that frequent nowadays). – SJuan76 Jun 22 '13 at 15:34
  • :) np I understand. In my experience the code I posted works very well in production on Android devices to do exactly what the user asked. – Ken Wolf Jun 22 '13 at 15:35