【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" />
相关推荐
fatiaozhang952712 小时前
晶晨S905L3SB芯片_安卓9.0_高安版_支持外置WIFI_线刷固件包
android·华为·电视盒子·刷机固件·机顶盒刷机
旋律逍遥13 小时前
《AOSP上手》 2、Framework 开发小需求 “去掉原生 Launcher 中的 google 搜索栏”
android
liulilittle13 小时前
在 Android Shell 终端上直接运行 OPENPPP2 网关路由配置指南
android·linux·开发语言·网络·c++·编程语言·通信
低调小一13 小时前
KuiklyUI 科普:UI 如何映射到 Android View 并完成渲染
android·windows·ui
火柴就是我13 小时前
android shadertoy效果 转换成 Android动态壁纸的写法
android
Bryce李小白14 小时前
Kotlin Flow 的使用
android·开发语言·kotlin
氦客16 小时前
Android Compose 状态的概念
android·compose·重组·状态·组合·mutablestate·mutablestateof
Jerry16 小时前
Compose 约束条件和修饰符顺序
android
千里马学框架18 小时前
安卓系统中线程优先级Priority查看方式汇总
android·framework·线程·安卓framework开发·优先级·priority
沐怡旸18 小时前
【Android】Handler/Looper机制相关的类图和流程图
android