【问题标题】:How to feed the IP of the device automatically in android如何在android中自动提供设备的IP
【发布时间】:2019-11-19 17:46:27
【问题描述】:

目前,我正在手动提供模拟器 IP 地址。经过一番研究,我发现如果我的设备连接到 Wifi,我可以使用以下方法。

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE); String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

但在我的情况下它没有连接到wifi(连接到局域网),在这种情况下我该怎么做?

这是我目前所拥有的。我想让我的应用自动选择其 IP 地址。

String url = "0.0.0.0"; // emulator ip MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(url);

【问题讨论】:

  • 尝试使用 127.0.0.1 作为 ip
  • 我不想手动输入 Ip。我想自动获得。如果我提供本地 IP,它会自动选择吗?是这个意思吗?

标签: java android ip-address android-networking


【解决方案1】:
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()) {
                String ip = inetAddress.getHostAddress();
                Log.i(TAG, "***** IP="+ ip);
                return ip;
            }
        }
    }
} catch (SocketException ex) {
    Log.e(TAG, ex.toString());
}
return null;
}

使用 getHostAddress :IP=fe70::75ca:a16d:ea5a:.......

使用 hashCode 和 Formatter 你会得到实际的 IP。

【讨论】:

  • 感谢您的回答。我有问题formatIpAddress() 似乎已弃用API。它会完成这项工作吗?
  • 弃用是因为该函数不支持 ipv6 和 WifiInfo。只需使用 formatIpAddress() 因为它有效并添加 @SuppressWarnings("deprecation") 以消除警告。谢谢你
  • 是的,你可以像上面那样给出。
  • 如果是 xampp,请确保可以公开访问。
  • 那就试试这个android-examples.com/…
【解决方案2】:

Varma Lanke 的回答很好。但它以相反的顺序返回 IP。为了解决这个问题

代替这一行

String ip = Formatter.formatIpAddress(inetAddress.hashCode());

使用这个

String ip = inetAddress.getHostAddress();

了解更多详情。看看这里getting device Ip

【讨论】:

    猜你喜欢
    • 2012-12-10
    • 1970-01-01
    • 2011-03-22
    • 2012-10-22
    • 1970-01-01
    • 2023-03-04
    • 2015-09-01
    • 2018-06-11
    • 2011-03-24
    相关资源
    最近更新 更多