InetAddress.getLocalHost()。getHostAddress()在Android中返回127.0.0.1

时间:2012-02-03 11:33:44

标签: android sockets network-programming

我的应用程序使用多播来发送信标以及协议消息和加入多播组的主机的IP。在Android设备中,它返回127.0.0.1。我环顾四周,发现有很多人建议更改主机文件。但是,在android的情况下,在我的上下文中是不可能的。如何获得设备的真实IP,而不是环回地址..

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

3 个答案:

答案 0 :(得分:13)

修改了几个位,这个位用于获取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());

答案 1 :(得分:0)

试试这个: -

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

答案 2 :(得分:0)

从我的尝试来看,我能得到的最大值是wifi网络地址。

我不知道任何其他方式,而不是实际调用返回IP地址的网络服务器。显然,问题在于它使用手机数据。

相关问题