【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" />
相关推荐
zhangguojia71 小时前
Activity启动流程(四):从setContentView到View树创建与Window挂载
android
三少爷的鞋3 小时前
Kotlin 2026:裁员、AI、Rust——黄金时代结束了吗?Jake Wharton 为你解答
android
alexhilton3 小时前
从零开始的架构测试套件
android·kotlin·android jetpack
finhaz5 小时前
台电x98plus在安卓x86的使用
android·平板·安卓x86
事圆则缓5 小时前
遗留项目改造实战指南:从可读性、代码质量到性能和 AI 约束
android·ai·代码规范
mmsx5 小时前
Android 手簿 ADB 无线调试全攻略:USB 转 WiFi 一键连接
android·前端
律宏阔6 小时前
Android WebRTC + H.265 适配记录
android
mmsx6 小时前
MapLibre 实战 08|GPS 点漂了几百米才被发现:GCJ-02 纠偏原理与"转两次"陷阱
android·前端
春夏与冬6 小时前
Android : apktool
android