Milan
Milan

Reputation: 1875

InetAddress.getLocalHost().getHostAddress() returns 127.0.0.1 in Android

My application uses multicast to send a beacon in periods along with protocol message and ip of the host joining the multicast group. In android device it is returning 127.0.0.1. I have looked around and found that many people suggested changing a host file. But, in case of android it is not possible in my context. How do I get real IP of the device, not the loopback address..

private void getLocalAddress()
{
    try {
        String localHost = InetAddress.getLocalHost().getHostAddress();
        servers.add(localHost);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}

Upvotes: 7

Views: 14366

Answers (3)

Milan
Milan

Reputation: 1875

Modified few bits and this one is working as desired for getting IPv4 addresses. !inetAddress.isLoopbackAddress() removes all the loopback address. !inetAddress.isLinkLocalAddress() and inetAddress.isSiteLocalAddress()) removes all IPv6 addresses. I hope this will help someone in here.

    StringBuilder IFCONFIG=new StringBuilder();
    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() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
                IFCONFIG.append(inetAddress.getHostAddress().toString()+"\n");
                }

            }
        }
    } catch (SocketException ex) {
        Log.e("LOG_TAG", ex.toString());
    }
    servers.add(IFCONFIG.toString());

Upvotes: 14

Rafael Sanches
Rafael Sanches

Reputation: 1823

From my tries, the maximum I could get was the wifi network address.

I don't know any other way rather than actually calling a webserver that returns the ip address. Obviously, the problem with this is that it uses the phone data.

Upvotes: 0

himanshu
himanshu

Reputation: 1980

Try this:-

String hostname = args[0];
try 
    {
      InetAddress ipaddress = InetAddress.getByName(hostname);
      System.out.println("IP address: " + ipaddress.getHostAddress());
    }
    catch ( UnknownHostException e )
    {
      System.out.println("Could not find IP address for: " + hostname);
    }

Upvotes: 0

Related Questions