I recently had a need to know the IP address of my phone when it was attached to my local network. I thought that this would be easy – just use the WifiManager – right? Get the WifiInfo then call getIPAddress() and that should give me what I needed. Well I was wrong…

The documentation in the developers area does not show any information for the method getIPAddress() all it states is that it returns an int? I was not sure that this would give me what I needed – maybe I would have to parse the number to return a logical display of the IP.

Well… after a few hours of trying different ways to display the number and looking at different ways that others have tried, I could not come up with a way to display the number returned by this method.

Back to searching for another way to do this. I abandon looking through the Android docs for a way and moved on to just look at how others have done this through Java calls – and wouldn’t you know I found a way.

By simply iterating over the network interfaces I was  able to get the IP that I was looking for. I can’t take full credit for this code as others have done this before me. One thing I need to remeber is that if there is not a way directly in the Android implementation – there might just be a simple Java method to solve my issue!

Here is the code that I used to get my local IP:

private 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) {
            return "ERROR Obtaining IP";
        }
        return "No IP Available";  
    }