【问题标题】:Return ALL available IP addresses for an Android device?返回 Android 设备的所有可用 IP 地址?
【发布时间】:2013-05-30 01:50:53
【问题描述】:

我需要列出任何特定 Android 设备的所有可用 IP 地址。

我找到了一些示例代码,但这只会返回一个 IP 地址,它恰好是一个 IPv6 地址。我需要获取任何特定设备的所有可用 IP。我在这个应用程序的 iOS 版本上做了同样的事情,它返回 3 个 IPv6 地址,一个 192. 地址和一个 10. 地址。我正在尝试在 Android 上复制相同的内容。我将所有值传递给一个数组并将它们显示在一个列表中。

我的代码是:

public String getLocalIpAddress()
{
    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()) {
                    IPAddresses.setText(inetAddress.getHostAddress().toString());
                    return inetAddress.getHostAddress().toString();
                }
            }
         }
    } catch (SocketException ex) {
        String LOG_TAG = null;
        Log.e(LOG_TAG, ex.toString());
    }

    return null;
}

【问题讨论】:

    标签: android arrays return ip-address


    【解决方案1】:

    在我看来,您的代码只是返回了第一个匹配项 - 这不是问题吗?我本来希望你建立地址列表,并返回它而不是一个字符串。像这样的:

    public String[] getLocalIpAddress()
    {          
        ArrayList<String> addresses = new ArrayList<String>();
        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()) {
                        IPAddresses.setText(inetAddress.getHostAddress().toString());
                        addresses.add(inetAddress.getHostAddress().toString());
                    }
                 }
             }
         } catch (SocketException ex) {
             String LOG_TAG = null;
             Log.e(LOG_TAG, ex.toString());
         }
         return addresses.toArray(new String[0]);
    }
    

    我不确定 IPAddresses.setText 调用在做什么,所以我把它留在了,但我希望它也需要以某种方式进行调整,以处理您可能有多个地址被匹配的事实.

    【讨论】:

    • 我正在尝试您的解决方案并尝试将返回的值传递给一个数组,但没有成功。我正在尝试: String[] ipArray = new String[] { getLocalIpAddress() };我在 iOS 上已经有一段时间了,回到 Android 有点生疏了!
    • String[] ipArray = getLocalIpAddress(); 应该是您需要做的所有事情。
    猜你喜欢
    • 1970-01-01
    • 2019-11-13
    • 2012-03-11
    • 2018-05-16
    • 2016-01-06
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多