如何从代码中获取设备的 IP 地址?

新手上路,请多包涵

是否可以使用某些代码获取设备的 IP 地址?

原文由 Nilesh Tupe 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 366
2 个回答

经许可 ACCESS_WIFI_STATEAndroidManifest.xml --- 中声明:

 <uses-permission
    android:name="android.permission.ACCESS_WIFI_STATE"/>

可以使用 WifiManager 获取IP地址:

 Context context = requireContext().getApplicationContext();
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

原文由 Nilesh Tupe 发布,翻译遵循 CC BY-SA 4.0 许可协议

Blockquote //获取设备IP地址

open fun getLocalIpAddress(): String? {
    try {
        val en: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()
        while (en.hasMoreElements()) {
            val networkInterface: NetworkInterface = en.nextElement()
            val enumerationIpAddress: Enumeration<InetAddress> = networkInterface.inetAddresses
            while (enumerationIpAddress.hasMoreElements()) {
                val inetAddress: InetAddress = enumerationIpAddress.nextElement()
                if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                    return inetAddress.getHostAddress()
                }
            }
        }
    } catch (ex: SocketException) {
        ex.printStackTrace()
    }
    return null
}

原文由 Rajnish Kumar Tripathi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题