【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" />
相关推荐
xvch2 小时前
Kotlin 2.1.0 入门教程(二十五)类型擦除
android·kotlin
simplepeng10 小时前
我的天,我真是和androidx的字体加载杠上了
android
小猫猫猫◍˃ᵕ˂◍11 小时前
备忘录模式:快速恢复原始数据
android·java·备忘录模式
CYRUS_STUDIO13 小时前
使用 AndroidNativeEmu 调用 JNI 函数
android·逆向·汇编语言
梦否13 小时前
【Android】类加载器&热修复-随记
android
徒步青云14 小时前
Java内存模型
android
今阳14 小时前
鸿蒙开发笔记-6-装饰器之@Require装饰器,@Reusable装饰器
android·app·harmonyos
-优势在我19 小时前
Android TabLayout 实现随意控制item之间的间距
android·java·ui
hedalei19 小时前
android13修改系统Launcher不跟随重力感应旋转
android·launcher
Indoraptor20 小时前
Android Fence 同步框架
android