【问题标题】:Internal IP address when not on Wi-Fi未连接 Wi-Fi 时的内部 IP 地址
【发布时间】:2026-01-28 04:30:01
【问题描述】:

我在连接到 Wi-Fi 时使用它来获取内部 IP:

            WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();

            int ipv4intAddress = wifiInfo.getIpAddress();
            tempView = (TextView) findViewById(R.id.textViewIPv4Int2);
            tempView.setText(myNetworkOperations.iptoDecimal(ipv4intAddress));

在使用移动设备或其他类型的连接时,是否有类似的简单方法来获取该 IP?

【问题讨论】:

标签: android ip-address


【解决方案1】:

你可以试试这段代码:

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()) {
                return inetAddress.getHostAddress().toString();
            }
        }
    }
} catch (SocketException ex) {
    return "ERROR Obtaining IP";
}
return "No IP Available";

【讨论】:

  • 这似乎可行,谢谢。但是我怎么知道它是正确的界面呢?我猜可能有好几个。
最近更新 更多