【问题标题】:InetAddress.getLocalHost().getHostAddress() returns 127.0.0.1 in AndroidInetAddress.getLocalHost().getHostAddress() 在 Android 中返回 127.0.0.1
【发布时间】:2012-02-26 00:48:25
【问题描述】:

我的应用程序使用多播在周期内发送信标以及协议消息和加入多播组的主机的 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();
    }
}

【问题讨论】:

  • 在我的手机上,除非它已激活 Wi-Fi 并连接到 Wi-Fi 网络,否则它没有 IP 地址。如果没有本地地址,则getLocalHost 返回环回地址,这就是你得到的。
  • @JoachimPileborg 试试我的答案。我希望这能解决你的问题。

标签: android sockets network-programming


【解决方案1】:

修改了一些位,这一位可以根据需要工作以获取 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());

【讨论】:

  • 只是为了确保没有人忘记它,你需要在你的 AndroidManifest.xml 上获得 INTERNET 权限:
  • 为什么在这里使用\n
【解决方案2】:

试试这个:-

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

【讨论】:

  • 我的应用程序何时发货..您认为如何为使用该应用程序的所有用户提供主机名?你知道其他方法可以找到它吗?
【解决方案3】:

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

除了实际调用返回 IP 地址的网络服务器外,我不知道任何其他方法。显然,问题在于它使用了电话数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 2011-11-15
    • 2011-01-23
    相关资源
    最近更新 更多