public class IpGetUtil {
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 {
//Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
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 = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
return ipAddress;
}
} else {
//当前无网络连接,请在设置中打开网络
}
return null;
} /**
* 将得到的int类型的IP转换为String类型
*
* @param ip
* @return
*/
public static String intIP2StringIP(int ip) {
return (ip & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
(ip >> 24 & 0xFF);
}
}

转载自http://blog.csdn.net/aiynmimi/article/details/52625709

最新文章

  1. 如何直接在 PC 端获取其它端设备的 UserAgent 信息呢?
  2. JS string 截取
  3. [Word]中批量修改图片大小和缩放比例方法
  4. wpf打开文夹和打开文件
  5. [已解决] 快速理解RSA算法
  6. C语言面试题
  7. GitHub 初探
  8. Duilib实现圆形头像控件
  9. poj2492 带权并查集
  10. 白盒测试之gmock入门篇
  11. hdu4778:状压dp+博弈
  12. strcpy, mencpy, memmove三者区别
  13. dell N5010
  14. 十、VueJs 填坑日记之在项目中使用Amaze UI
  15. Java集合框架之四大接口、常用实现类
  16. java工厂设计模式初步
  17. 安卓开发过程中空指针的问题Java.lang.NullPointerException
  18. spring jar包解读(转)
  19. linux的压缩解压命令全解
  20. [转帖]关于网络编程中MTU、TCP、UDP优化配置的一些总结

热门文章

  1. Java并发编程原理与实战十七:AQS实现重入锁
  2. php按照指定顺序的排序
  3. Git Cannot rebase: You have unstaged changes.
  4. 同一条sql语句,只是改变了搜索的条件,就很慢?
  5. Linux常用的20个命令
  6. 【leetcode 简单】 第一百一十题 分发饼干
  7. Mysql服务优化
  8. js鼠标自定移入输入框文本框光标自动定位到文本框
  9. Python 控制流、列表生成式
  10. 《区块链100问》第82集:应用类项目Golem