在wifi环境下,可以通过WifiInfo来获取设备的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;}

更多相关文章

  1. android 如何遍历Cursor
  2. Android 使用OKHttp3请求接口401,返回Authorization Required错误
  3. android - Jni 接口函数表
  4. 【译】Android 6.0接口变化(二)(Android 6.0 Changes)
  5. 获取Android各类系统相关信息的接口实现代码
  6. Android Studio自动化快速实现Parcelable接口序列化
  7. Android 接口定义语言AIdl

随机推荐

  1. android强制隐藏输入法键盘(亲测可用,欢迎
  2. Android中点击按钮的事件处理实现步骤
  3. 反编译出错
  4. Android通过换载体实现再次辉煌
  5. Android中全屏无标题设置
  6. Visibility属性中invisible和gone 区别
  7. Android GPS相关文章
  8. android 用tcpdump抓取网络包
  9. Android--通过ContentResolver取得com.an
  10. Android(安卓)keystore 签名证书的作用以