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

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

private void getLocalAddress()
{
    try {
        String localHost = InetAddress.getLocalHost().getHostAddress();
        servers.add(localHost);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}
+5
source share
3 answers

, IPv4.! inetAddress.isLoopbackAddress() .! inetAddress.isLinkLocalAddress() inetAddress.isSiteLocalAddress()) IPv6. , - .

    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());
+12

: -

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);
    }
0

Of my attempts, the maximum I could get was the wifi network address.

I do not know another way, but I am not calling a web server that returns an ip address. Obviously, the problem is that it uses phone data.

0
source

All Articles