【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" />
相关推荐
张风捷特烈1 小时前
每日一题 Flutter#5,6 | 两道 Widget 选择题
android·flutter
移动开发者1号1 小时前
App主界面点击与跳转启动方式区别
android·kotlin
移动开发者1号1 小时前
我用Intent传大图片时竟然崩了,怎么回事啊
android·kotlin
androidwork13 小时前
Android LinearLayout、FrameLayout、RelativeLayout、ConstraintLayout大混战
android·java·kotlin·androidx
每次的天空13 小时前
Android第十三次面试总结基础
android·面试·职场和发展
wu_android13 小时前
Android 相对布局管理器(RelativeLayout)
android
李斯维15 小时前
循序渐进 Android Binder(二):传递自定义对象和 AIDL 回调
android·java·android studio
androidwork15 小时前
OkHttp 3.0源码解析:从设计理念到核心实现
android·java·okhttp·kotlin
像风一样自由16 小时前
【001】frida API分类 总览
android·frida
casual_clover16 小时前
Android 之 kotlin 语言学习笔记四(Android KTX)
android·学习·kotlin