Android中获取设备的IP
16lz
2021-01-23
在wifi环境下,可以通过WifiInfo来获取设备的ip
执行上面的代码需要
当然也可通过jdk总的NetworkInterface来获取的,就是遍历所有的网络接口,获取到非loopback ip
public String getIpAddress() {WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);WifiInfo wifiInfo = wifiManager.getConnectionInfo();int ipAddress = wifiInfo.getIpAddress();int[] ipAddr = new int[4];ipAddr[0] = ipAddress & 0xFF;ipAddr[1] = (ipAddress >> 8) & 0xFF;ipAddr[2] = (ipAddress >> 16) & 0xFF;ipAddr[3] = (ipAddress >> 24) & 0xFF;return new StringBuilder().append(ipAddr[0]).append(".").append(ipAddr[1]).append(".").append(ipAddr[2]).append(".").append(ipAddr[3]).append(".").toString();}
执行上面的代码需要
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
当然也可通过jdk总的NetworkInterface来获取的,就是遍历所有的网络接口,获取到非loopback ip
public String getLocalIpAddress() {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()) {return inetAddress.getHostAddress().toString();}}}} catch (SocketException ex) {Log.e("", ex.toString());}return null;}
更多相关文章
- android 如何遍历Cursor
- Android 使用OKHttp3请求接口401,返回Authorization Required错误
- android - Jni 接口函数表
- 【译】Android 6.0接口变化(二)(Android 6.0 Changes)
- 获取Android各类系统相关信息的接口实现代码
- Android Studio自动化快速实现Parcelable接口序列化
- Android 接口定义语言AIdl