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

13,213

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());
Share:
13,213
Milan
Author by

Milan

Updated on June 20, 2022

Comments

  • Milan
    Milan almost 2 years

    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();
        }
    }
    
  • Milan
    Milan about 12 years
    when my application is shipped..how do you think will it be possible to provide hostname for all users using the app? Do you know any other way to find it?
  • Alexandre Schmidt
    Alexandre Schmidt over 7 years
    Just to make sure no one forget about it, you'll need INTERNET permission on your AndroidManifest.xml: <uses-permission android:name="android.permission.INTERNET" />
  • Adeel Zafar
    Adeel Zafar over 4 years
    Why do you use \n here.