今天开发用到一个不常用的知识点,特此记录下,获取设备的 IP 地址。
话不多说,上代码,直接判断网络环境,获取对应的 ip
public static String getIPAddress(Context context) { NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); if (info != null && info.isConnected()) { if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络 try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { return inetAddress.getHostAddress(); } } } } catch (SocketException e) { e.printStackTrace(); } } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络 WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String ipAddress = Formatter.formatIpAddress(wifiInfo.getIpAddress()); return ipAddress; } } else { //未连接网络,提示用户 Toast.makeText(context, "无网络", Toast.LENGTH_SHORT).show(); } return null; }
得注意的是 wifi 环境下获取的 ip 的局域网的 ip 地址,并不是外网的地址,如需获取外网的地址还需请求额外的接口。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于