安卓手机获取IP地址

女爷i 2022-03-30 17:53 450阅读 0赞
  1. public class IpGetUtil {
  2. public static String getIPAddress(Context context) {
  3. NetworkInfo info = ((ConnectivityManager) context
  4. .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
  5. if (info != null && info.isConnected()) {
  6. if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
  7. //当前使用2G/3G/4G网络
  8. try {
  9. //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
  10. for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
  11. NetworkInterface intf = en.nextElement();
  12. for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
  13. InetAddress inetAddress = enumIpAddr.nextElement();
  14. if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
  15. return inetAddress.getHostAddress();
  16. }
  17. }
  18. }
  19. } catch (SocketException e) {
  20. e.printStackTrace();
  21. }
  22. } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
  23. //当前使用无线网络
  24. WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  25. WifiInfo wifiInfo = wifiManager.getConnectionInfo();
  26. String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
  27. return ipAddress;
  28. }
  29. } else {
  30. //当前无网络连接,请在设置中打开网络
  31. }
  32. return null;
  33. }
  34. /**
  35. * 将得到的int类型的IP转换为String类型
  36. *
  37. * @param ip
  38. * @return
  39. */
  40. public static String intIP2StringIP(int ip) {
  41. return (ip & 0xFF) + "." +
  42. ((ip >> 8) & 0xFF) + "." +
  43. ((ip >> 16) & 0xFF) + "." +
  44. (ip >> 24 & 0xFF);
  45. }
  46. }

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

发表评论

表情:
评论列表 (有 0 条评论,450人围观)

还没有评论,来说两句吧...

相关阅读

    相关 手机图标尺寸

      应用程序图标 (Icon)应当是一个 Alpha 通道透明的32位 PNG 图片。由于安卓设备众多,一个应用程序图标需要设计几种不同大小,如: LDPI (Low

    相关 adb控制手机

           最近做项目发现同事做的Api能够让电脑通过USB控制手机进行操作,原来用的是谷歌开发的adb。简单说一下如何控制手机拍照吧,其他的以后接触到了再补上。