【Android】获取设备IP的方法

序言

在Android开发中,有很多地方需要使用IP地址,但是有时候Android设备获取的IP地址是有区别的,比如如果Android设备创建一个热点,那此时这个Android设备就有两个IP地址了,一个是本身的IP地址,一个是热点的路由器IP地址,这个获取方式是不一样的。

获取本机IP地址
java 复制代码
try {
    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    if (wifiManager != null) {
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ipHostAddress = Formatter.formatIpAddress(ipAddress);
        Log.e(TAG, "本机IP:" + ipHostAddress);
    }
} catch (Exception e) {
    AgLog.printException(e);
}
获取路由器IP地址
java 复制代码
try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (!address.isLoopbackAddress() && !address.isLinkLocalAddress() && address.isSiteLocalAddress()) {
                        // 返回第一个非回环、非链路本地地址
                        ipHostAddress = address.getHostAddress();
                        Log.e(TAG, "本机IP:" + ipHostAddress);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            AgLog.printException(e);
        }

另外需要注意,需要先设置权限,再获取IP地址

xml 复制代码
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
相关推荐
阿巴斯甜16 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker16 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq952717 小时前
Andorid Google 登录接入文档
android
黄林晴19 小时前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab1 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读
城东米粉儿1 天前
Android MediaPlayer 笔记
android
Jony_1 天前
Android 启动优化方案
android
阿巴斯甜1 天前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android
张小潇1 天前
AOSP15 Input专题InputReader源码分析
android
_小马快跑_2 天前
Kotlin | 协程调度器选择:何时用CoroutineScope配置,何时用launch指定?
android