当前位置:   article > 正文

SpringBoot 封装Windows 性能监控_managementfactory 性能

managementfactory 性能

整体项目结构:

BlueSky 的pom.xml 文件:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.zzg</groupId>
  5. <artifactId>BuleSky</artifactId>
  6. <version>0.0.1-SNAPSHOT</version>
  7. <packaging>pom</packaging>
  8. <!--springboot 父类 -->
  9. <parent>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-parent</artifactId>
  12. <version>2.1.0.RELEASE</version>
  13. </parent>
  14. <properties>
  15. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  16. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <!--springboot 依赖web -->
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-web</artifactId>
  24. </dependency>
  25. <!--springboot 依赖test -->
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-test</artifactId>
  29. </dependency>
  30. <!--springboot 依赖devtool -->
  31. <dependency>
  32. <groupId>org.springframework.boot</groupId>
  33. <artifactId>spring-boot-devtools</artifactId>
  34. </dependency>
  35. <!--lombak 集成 -->
  36. <dependency>
  37. <groupId>org.projectlombok</groupId>
  38. <artifactId>lombok</artifactId>
  39. <version>1.18.0</version>
  40. </dependency>
  41. <!--apache common 工具包 -->
  42. <dependency>
  43. <groupId>commons-net</groupId>
  44. <artifactId>commons-net</artifactId>
  45. <version>3.6</version>
  46. </dependency>
  47. <dependency>
  48. <groupId>org.apache.commons</groupId>
  49. <artifactId>commons-lang3</artifactId>
  50. <version>3.8.1</version>
  51. </dependency>
  52. </dependencies>
  53. <modules>
  54. <module>common-ssh</module>
  55. <module>common-ftp</module>
  56. <module>common-fastdfs</module>
  57. <module>common-monitor-windows</module>
  58. <module>common-monitor_linux</module>
  59. <module>common-elasticsearch</module>
  60. </modules>
  61. </project>

common-monitor-windows 项目结构:

Application.java

  1. package com.zzg.common;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class Application {
  6. public static void main(String[] args) {
  7. // TODO Auto-generated method stub
  8. SpringApplication.run(Application.class, args);
  9. }
  10. }

Cpu.java

  1. package com.zzg.common.entity;
  2. import com.zzg.common.util.Arith;
  3. import lombok.Getter;
  4. import lombok.Setter;
  5. public class Cpu {
  6. /**
  7. * 核心数
  8. */
  9. @Getter
  10. @Setter
  11. private int cpuNum;
  12. /**
  13. * CPU总的使用率
  14. */
  15. @Setter
  16. private double total;
  17. /**
  18. * CPU系统使用率
  19. */
  20. @Setter
  21. private double sys;
  22. /**
  23. * CPU用户使用率
  24. */
  25. @Setter
  26. private double used;
  27. /**
  28. * CPU当前等待率
  29. */
  30. @Setter
  31. private double wait;
  32. /**
  33. * CPU当前空闲率
  34. */
  35. @Setter
  36. private double free;
  37. public double getTotal() {
  38. return Arith.round(Arith.mul(total, 100), 2);
  39. }
  40. public double getSys() {
  41. return Arith.round(Arith.mul(sys / total, 100), 2);
  42. }
  43. public double getUsed() {
  44. return Arith.round(Arith.mul(used / total, 100), 2);
  45. }
  46. public double getWait() {
  47. return Arith.round(Arith.mul(wait / total, 100), 2);
  48. }
  49. public double getFree() {
  50. return Arith.round(Arith.mul(free / total, 100), 2);
  51. }
  52. }

Jvm.java

  1. package com.zzg.common.entity;
  2. import java.lang.management.ManagementFactory;
  3. import com.zzg.common.util.Arith;
  4. import com.zzg.common.util.DateUtils;
  5. import lombok.Getter;
  6. import lombok.Setter;
  7. /**
  8. * 虚拟机相关设置
  9. * @author zzg
  10. *
  11. */
  12. public class Jvm {
  13. /**
  14. * 当前JVM占用的内存总数(M)
  15. */
  16. @Setter
  17. private double total;
  18. /**
  19. * JVM最大可用内存总数(M)
  20. */
  21. @Setter
  22. private double max;
  23. /**
  24. * JVM空闲内存(M)
  25. */
  26. @Setter
  27. private double free;
  28. /**
  29. * JDK版本
  30. */
  31. @Getter
  32. @Setter
  33. private String version;
  34. /**
  35. * JDK路径
  36. */
  37. @Getter
  38. @Setter
  39. private String home;
  40. public double getTotal() {
  41. return Arith.div(total, (1024 * 1024), 2);
  42. }
  43. public double getMax() {
  44. return Arith.div(max, (1024 * 1024), 2);
  45. }
  46. public double getFree() {
  47. return Arith.div(free, (1024 * 1024), 2);
  48. }
  49. public double getUsed() {
  50. return Arith.div(total - free, (1024 * 1024), 2);
  51. }
  52. public double getUsage() {
  53. return Arith.mul(Arith.div(total - free, total, 4), 100);
  54. }
  55. /**
  56. * 获取JDK名称
  57. */
  58. public String getName() {
  59. return ManagementFactory.getRuntimeMXBean().getVmName();
  60. }
  61. /**
  62. * JDK启动时间
  63. */
  64. public String getStartTime() {
  65. return DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getServerStartDate());
  66. }
  67. /**
  68. * JDK运行时间
  69. */
  70. public String getRunTime() {
  71. return DateUtils.getDatePoor(DateUtils.getNowDate(), DateUtils.getServerStartDate());
  72. }
  73. }

Mem.java

  1. package com.zzg.common.entity;
  2. import com.zzg.common.util.Arith;
  3. import lombok.Setter;
  4. /**
  5. * 内存相关信息
  6. * @author zzg
  7. *
  8. */
  9. public class Mem {
  10. /**
  11. * 内存总量
  12. */
  13. @Setter
  14. private double total;
  15. /**
  16. * 已用内存
  17. */
  18. @Setter
  19. private double used;
  20. /**
  21. * 剩余内存
  22. */
  23. @Setter
  24. private double free;
  25. public double getTotal() {
  26. return Arith.div(total, (1024 * 1024 * 1024), 2);
  27. }
  28. public double getUsed() {
  29. return Arith.div(used, (1024 * 1024 * 1024), 2);
  30. }
  31. public double getFree() {
  32. return Arith.div(free, (1024 * 1024 * 1024), 2);
  33. }
  34. public double getUsage() {
  35. return Arith.mul(Arith.div(used, total, 4), 100);
  36. }
  37. }

Sys.java

  1. package com.zzg.common.entity;
  2. import lombok.Getter;
  3. import lombok.Setter;
  4. /**
  5. * 系统相关信息
  6. * @author zzg
  7. *
  8. */
  9. public class Sys {
  10. /**
  11. * 服务器名称
  12. */
  13. @Getter
  14. @Setter
  15. private String computerName;
  16. /**
  17. * 服务器Ip
  18. */
  19. @Getter
  20. @Setter
  21. private String computerIp;
  22. /**
  23. * 项目路径
  24. */
  25. @Getter
  26. @Setter
  27. private String userDir;
  28. /**
  29. * 操作系统
  30. */
  31. @Getter
  32. @Setter
  33. private String osName;
  34. /**
  35. * 系统架构
  36. */
  37. @Getter
  38. @Setter
  39. private String osArch;
  40. }

SysFile.java

  1. package com.zzg.common.entity;
  2. import lombok.Getter;
  3. import lombok.Setter;
  4. /**
  5. * 系统文件相关信息
  6. * @author zzg
  7. *
  8. */
  9. public class SysFile {
  10. /**
  11. * 盘符路径
  12. */
  13. @Getter
  14. @Setter
  15. private String dirName;
  16. /**
  17. * 盘符类型
  18. */
  19. @Getter
  20. @Setter
  21. private String sysTypeName;
  22. /**
  23. * 文件类型
  24. */
  25. @Getter
  26. @Setter
  27. private String typeName;
  28. /**
  29. * 总大小
  30. */
  31. @Getter
  32. @Setter
  33. private String total;
  34. /**
  35. * 剩余大小
  36. */
  37. @Getter
  38. @Setter
  39. private String free;
  40. /**
  41. * 已经使用量
  42. */
  43. @Getter
  44. @Setter
  45. private String used;
  46. /**
  47. * 资源的使用率
  48. */
  49. @Getter
  50. @Setter
  51. private double usage;
  52. }

Server.java

  1. package com.zzg.common.server;
  2. import java.io.Serializable;
  3. import java.net.UnknownHostException;
  4. import java.util.LinkedList;
  5. import java.util.List;
  6. import java.util.Properties;
  7. import com.zzg.common.entity.Cpu;
  8. import com.zzg.common.entity.Jvm;
  9. import com.zzg.common.entity.Mem;
  10. import com.zzg.common.entity.Sys;
  11. import com.zzg.common.entity.SysFile;
  12. import com.zzg.common.util.Arith;
  13. import com.zzg.common.util.IpUtils;
  14. import lombok.Getter;
  15. import lombok.Setter;
  16. import oshi.SystemInfo;
  17. import oshi.hardware.CentralProcessor;
  18. import oshi.hardware.GlobalMemory;
  19. import oshi.hardware.HardwareAbstractionLayer;
  20. import oshi.hardware.CentralProcessor.TickType;
  21. import oshi.software.os.FileSystem;
  22. import oshi.software.os.OSFileStore;
  23. import oshi.software.os.OperatingSystem;
  24. import oshi.util.Util;
  25. public class Server implements Serializable {
  26. /**
  27. *
  28. */
  29. private static final long serialVersionUID = 1L;
  30. private static final int OSHI_WAIT_SECOND = 1000;
  31. /**
  32. * CPU相关信息
  33. */
  34. @Getter
  35. @Setter
  36. private Cpu cpu = new Cpu();
  37. /**
  38. * 內存相关信息
  39. */
  40. @Getter
  41. @Setter
  42. private Mem mem = new Mem();
  43. /**
  44. * JVM相关信息
  45. */
  46. @Getter
  47. @Setter
  48. private Jvm jvm = new Jvm();
  49. /**
  50. * 服务器相关信息
  51. */
  52. @Getter
  53. @Setter
  54. private Sys sys = new Sys();
  55. /**
  56. * 磁盘相关信息
  57. */
  58. @Getter
  59. @Setter
  60. private List<SysFile> sysFiles = new LinkedList<SysFile>();
  61. public void copyTo() throws Exception {
  62. SystemInfo si = new SystemInfo();
  63. HardwareAbstractionLayer hal = si.getHardware();
  64. setCpuInfo(hal.getProcessor());
  65. setMemInfo(hal.getMemory());
  66. setSysInfo();
  67. setJvmInfo();
  68. setSysFiles(si.getOperatingSystem());
  69. }
  70. /**
  71. * 设置CPU信息
  72. */
  73. private void setCpuInfo(CentralProcessor processor) {
  74. // CPU信息
  75. long[] prevTicks = processor.getSystemCpuLoadTicks();
  76. Util.sleep(OSHI_WAIT_SECOND);
  77. long[] ticks = processor.getSystemCpuLoadTicks();
  78. long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
  79. long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
  80. long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
  81. long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
  82. long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
  83. long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
  84. long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
  85. long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
  86. long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
  87. cpu.setCpuNum(processor.getLogicalProcessorCount());
  88. cpu.setTotal(totalCpu);
  89. cpu.setSys(cSys);
  90. cpu.setUsed(user);
  91. cpu.setWait(iowait);
  92. cpu.setFree(idle);
  93. }
  94. /**
  95. * 设置内存信息
  96. */
  97. private void setMemInfo(GlobalMemory memory) {
  98. mem.setTotal(memory.getTotal());
  99. mem.setUsed(memory.getTotal() - memory.getAvailable());
  100. mem.setFree(memory.getAvailable());
  101. }
  102. /**
  103. * 设置服务器信息
  104. */
  105. private void setSysInfo() {
  106. Properties props = System.getProperties();
  107. sys.setComputerName(IpUtils.getHostName());
  108. sys.setComputerIp(IpUtils.getHostIp());
  109. sys.setOsName(props.getProperty("os.name"));
  110. sys.setOsArch(props.getProperty("os.arch"));
  111. sys.setUserDir(props.getProperty("user.dir"));
  112. }
  113. /**
  114. * 设置Java虚拟机
  115. */
  116. private void setJvmInfo() throws UnknownHostException {
  117. Properties props = System.getProperties();
  118. jvm.setTotal(Runtime.getRuntime().totalMemory());
  119. jvm.setMax(Runtime.getRuntime().maxMemory());
  120. jvm.setFree(Runtime.getRuntime().freeMemory());
  121. jvm.setVersion(props.getProperty("java.version"));
  122. jvm.setHome(props.getProperty("java.home"));
  123. }
  124. /**
  125. * 设置磁盘信息
  126. */
  127. private void setSysFiles(OperatingSystem os) {
  128. FileSystem fileSystem = os.getFileSystem();
  129. OSFileStore[] fsArray = fileSystem.getFileStores();
  130. for (OSFileStore fs : fsArray) {
  131. long free = fs.getUsableSpace();
  132. long total = fs.getTotalSpace();
  133. long used = total - free;
  134. SysFile sysFile = new SysFile();
  135. sysFile.setDirName(fs.getMount());
  136. sysFile.setSysTypeName(fs.getType());
  137. sysFile.setTypeName(fs.getName());
  138. sysFile.setTotal(convertFileSize(total));
  139. sysFile.setFree(convertFileSize(free));
  140. sysFile.setUsed(convertFileSize(used));
  141. sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100));
  142. sysFiles.add(sysFile);
  143. }
  144. }
  145. /**
  146. * 字节转换
  147. *
  148. * @param size 字节大小
  149. * @return 转换后值
  150. */
  151. public String convertFileSize(long size) {
  152. long kb = 1024;
  153. long mb = kb * 1024;
  154. long gb = mb * 1024;
  155. if (size >= gb) {
  156. return String.format("%.1f GB" , (float) size / gb);
  157. } else if (size >= mb) {
  158. float f = (float) size / mb;
  159. return String.format(f > 100 ? "%.0f MB" : "%.1f MB" , f);
  160. } else if (size >= kb) {
  161. float f = (float) size / kb;
  162. return String.format(f > 100 ? "%.0f KB" : "%.1f KB" , f);
  163. } else {
  164. return String.format("%d B" , size);
  165. }
  166. }
  167. }

Arith.java

  1. package com.zzg.common.util;
  2. import java.math.BigDecimal;
  3. /**
  4. * 精度计算工具
  5. * @author zzg
  6. *
  7. */
  8. public class Arith {
  9. /**
  10. * 默认除法运算精度
  11. */
  12. private static final int DEF_DIV_SCALE = 10;
  13. /**
  14. * 这个类不能实例化
  15. */
  16. private Arith() {
  17. }
  18. /**
  19. * 提供精确的加法运算。
  20. *
  21. * @param v1 被加数
  22. * @param v2 加数
  23. * @return 两个参数的和
  24. */
  25. public static double add(double v1, double v2) {
  26. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  27. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  28. return b1.add(b2).doubleValue();
  29. }
  30. /**
  31. * 提供精确的减法运算。
  32. *
  33. * @param v1 被减数
  34. * @param v2 减数
  35. * @return 两个参数的差
  36. */
  37. public static double sub(double v1, double v2) {
  38. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  39. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  40. return b1.subtract(b2).doubleValue();
  41. }
  42. /**
  43. * 提供精确的乘法运算。
  44. *
  45. * @param v1 被乘数
  46. * @param v2 乘数
  47. * @return 两个参数的积
  48. */
  49. public static double mul(double v1, double v2) {
  50. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  51. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  52. return b1.multiply(b2).doubleValue();
  53. }
  54. /**
  55. * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
  56. * 小数点以后10位,以后的数字四舍五入。
  57. *
  58. * @param v1 被除数
  59. * @param v2 除数
  60. * @return 两个参数的商
  61. */
  62. public static double div(double v1, double v2) {
  63. return div(v1, v2, DEF_DIV_SCALE);
  64. }
  65. /**
  66. * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
  67. * 定精度,以后的数字四舍五入。
  68. *
  69. * @param v1 被除数
  70. * @param v2 除数
  71. * @param scale 表示表示需要精确到小数点以后几位。
  72. * @return 两个参数的商
  73. */
  74. public static double div(double v1, double v2, int scale) {
  75. if (scale < 0) {
  76. throw new IllegalArgumentException(
  77. "The scale must be a positive integer or zero");
  78. }
  79. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  80. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  81. if (BigDecimal.ZERO.compareTo(b1.multiply(b2)) == 0){
  82. return BigDecimal.ZERO.doubleValue();
  83. }
  84. return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
  85. }
  86. /**
  87. * 提供精确的小数位四舍五入处理。
  88. *
  89. * @param v 需要四舍五入的数字
  90. * @param scale 小数点后保留几位
  91. * @return 四舍五入后的结果
  92. */
  93. public static double round(double v, int scale) {
  94. if (scale < 0) {
  95. throw new IllegalArgumentException(
  96. "The scale must be a positive integer or zero");
  97. }
  98. BigDecimal b = new BigDecimal(Double.toString(v));
  99. BigDecimal one = new BigDecimal("1");
  100. return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
  101. }
  102. }

DateUtils.java

  1. package com.zzg.common.util;
  2. import java.lang.management.ManagementFactory;
  3. import java.text.ParseException;
  4. import java.text.SimpleDateFormat;
  5. import java.util.Date;
  6. import org.apache.commons.lang3.ObjectUtils;
  7. import org.apache.commons.lang3.time.DateFormatUtils;
  8. /**
  9. * 时间工具类
  10. * @author zzg
  11. *
  12. */
  13. public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
  14. public static final String YYYY = "yyyy" ;
  15. public static final String YYYY_MM = "yyyy-MM" ;
  16. public static final String YYYY_MM_DD = "yyyy-MM-dd" ;
  17. public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss" ;
  18. public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss" ;
  19. private static String[] parsePatterns = {
  20. YYYY_MM_DD , YYYY_MM_DD_HH_MM_SS , "yyyy-MM-dd HH:mm" , YYYY_MM ,
  21. "yyyy/MM/dd" , "yyyy/MM/dd HH:mm:ss" , "yyyy/MM/dd HH:mm" , "yyyy/MM" ,
  22. "yyyy.MM.dd" , "yyyy.MM.dd HH:mm:ss" , "yyyy.MM.dd HH:mm" , "yyyy.MM"};
  23. /**
  24. * 获取当前Date型日期
  25. *
  26. * @return Date() 当前日期
  27. */
  28. public static Date getNowDate() {
  29. return new Date();
  30. }
  31. /**
  32. * 获取当前日期, 默认格式为yyyy-MM-dd
  33. *
  34. * @return String
  35. */
  36. public static String getDate() {
  37. return dateTimeNow(YYYY_MM_DD);
  38. }
  39. public static final String getTime() {
  40. return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
  41. }
  42. public static final String dateTimeNow() {
  43. return dateTimeNow(YYYYMMDDHHMMSS);
  44. }
  45. public static final String dateTimeNow(final String format) {
  46. return parseDateToStr(format, new Date());
  47. }
  48. public static final String dateTime(final Date date) {
  49. return parseDateToStr(YYYY_MM_DD, date);
  50. }
  51. public static final String parseDateToStr(final String format, final Date date) {
  52. if(ObjectUtils.allNotNull(date)){
  53. return new SimpleDateFormat(format).format(date);
  54. }
  55. return null;
  56. }
  57. /**
  58. * 日期路径 即年/月/日 如2018/08/08
  59. */
  60. public static final String datePath() {
  61. Date now = new Date();
  62. return DateFormatUtils.format(now, "yyyy/MM/dd");
  63. }
  64. /**
  65. * 日期路径 即年/月/日 如20180808
  66. */
  67. public static final String dateTime() {
  68. Date now = new Date();
  69. return DateFormatUtils.format(now, "yyyyMMdd");
  70. }
  71. /**
  72. * 日期型字符串转化为日期 格式
  73. */
  74. public static Date parseDate(Object str) {
  75. if (str == null) {
  76. return null;
  77. }
  78. try {
  79. return parseDate(str.toString(), parsePatterns);
  80. } catch (ParseException e) {
  81. return null;
  82. }
  83. }
  84. /**
  85. * 获取服务器启动时间
  86. */
  87. public static Date getServerStartDate() {
  88. long time = ManagementFactory.getRuntimeMXBean().getStartTime();
  89. return new Date(time);
  90. }
  91. /**
  92. * 计算两个时间差
  93. */
  94. public static String getDatePoor(Date endDate, Date nowDate) {
  95. long nd = (long)1000 * 24 * 60 * 60;
  96. long nh = (long)1000 * 60 * 60;
  97. long nm = (long)1000 * 60;
  98. // 获得两个时间的毫秒时间差异
  99. long diff = endDate.getTime() - nowDate.getTime();
  100. // 计算差多少天
  101. long day = diff / nd;
  102. // 计算差多少小时
  103. long hour = diff % nd / nh;
  104. // 计算差多少分钟
  105. long min = diff % nd % nh / nm;
  106. // 计算差多少秒//输出结果
  107. return day + "天" + hour + "小时" + min + "分钟" ;
  108. }
  109. }

IpUtils.java

  1. package com.zzg.common.util;
  2. import java.net.InetAddress;
  3. import java.net.UnknownHostException;
  4. import javax.servlet.http.HttpServletRequest;
  5. import lombok.extern.slf4j.Slf4j;
  6. @Slf4j
  7. public class IpUtils {
  8. public static final String LOCAL_IP="127.0.0.1";
  9. private IpUtils(){
  10. throw new IllegalStateException("Utility class");
  11. }
  12. public static String getIpAddr(HttpServletRequest request) {
  13. String unknown = "unknown";
  14. if (request == null) {
  15. return unknown;
  16. }
  17. String ip = request.getHeader("x-forwarded-for");
  18. if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
  19. ip = request.getHeader("Proxy-Client-IP");
  20. }
  21. if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
  22. ip = request.getHeader("X-Forwarded-For");
  23. }
  24. if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
  25. ip = request.getHeader("WL-Proxy-Client-IP");
  26. }
  27. if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
  28. ip = request.getHeader("X-Real-IP");
  29. }
  30. if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
  31. ip = request.getRemoteAddr();
  32. }
  33. return "0:0:0:0:0:0:0:1".equals(ip) ? LOCAL_IP : ip;
  34. }
  35. public static boolean internalIp(String ip) {
  36. byte[] addr = textToNumericFormatV4(ip);
  37. return internalIp(addr) || LOCAL_IP.equals(ip);
  38. }
  39. private static boolean internalIp(byte[] addr) {
  40. if(addr == null || addr.length<1){
  41. return false;
  42. }
  43. final byte b0 = addr[0];
  44. final byte b1 = addr[1];
  45. // 10.x.x.x/8
  46. final byte section1 = 0x0A;
  47. // 172.16.x.x/12
  48. final byte section2 = (byte) 0xAC;
  49. final byte section3 = (byte) 0x10;
  50. final byte section4 = (byte) 0x1F;
  51. // 192.168.x.x/16
  52. final byte section5 = (byte) 0xC0;
  53. final byte section6 = (byte) 0xA8;
  54. switch (b0) {
  55. case section1:
  56. return true;
  57. case section2:
  58. if (b1 >= section3 && b1 <= section4) {
  59. return true;
  60. }else {
  61. return false;
  62. }
  63. case section5:
  64. if(b1 == section6){
  65. return true;
  66. }else {
  67. return false;
  68. }
  69. default:
  70. return false;
  71. }
  72. }
  73. /**
  74. * 将IPv4地址转换成字节
  75. *
  76. * @param text IPv4地址
  77. * @return byte 字节
  78. */
  79. public static byte[] textToNumericFormatV4(String text) {
  80. byte[] emptyByte = new byte[0];
  81. if (text.length() == 0) {
  82. return emptyByte;
  83. }
  84. byte[] bytes = new byte[4];
  85. String[] elements = text.split("\\.", -1);
  86. try {
  87. long l;
  88. int i;
  89. switch (elements.length) {
  90. case 1:
  91. l = Long.parseLong(elements[0]);
  92. if ((l < 0L) || (l > 4294967295L)) {
  93. return emptyByte;
  94. }
  95. bytes[0] = (byte) (int) (l >> 24 & 0xFF);
  96. bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
  97. bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
  98. bytes[3] = (byte) (int) (l & 0xFF);
  99. break;
  100. case 2:
  101. l = Integer.parseInt(elements[0]);
  102. if ((l < 0L) || (l > 255L)) {
  103. return emptyByte;
  104. }
  105. bytes[0] = (byte) (int) (l & 0xFF);
  106. l = Integer.parseInt(elements[1]);
  107. if ((l < 0L) || (l > 16777215L)) {
  108. return emptyByte;
  109. }
  110. bytes[1] = (byte) (int) (l >> 16 & 0xFF);
  111. bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
  112. bytes[3] = (byte) (int) (l & 0xFF);
  113. break;
  114. case 3:
  115. for (i = 0; i < 2; ++i) {
  116. l = Integer.parseInt(elements[i]);
  117. if ((l < 0L) || (l > 255L)) {
  118. return emptyByte;
  119. }
  120. bytes[i] = (byte) (int) (l & 0xFF);
  121. }
  122. l = Integer.parseInt(elements[2]);
  123. if ((l < 0L) || (l > 65535L)) {
  124. return emptyByte;
  125. }
  126. bytes[2] = (byte) (int) (l >> 8 & 0xFF);
  127. bytes[3] = (byte) (int) (l & 0xFF);
  128. break;
  129. case 4:
  130. for (i = 0; i < 4; ++i) {
  131. l = Integer.parseInt(elements[i]);
  132. if ((l < 0L) || (l > 255L)) {
  133. return emptyByte;
  134. }
  135. bytes[i] = (byte) (int) (l & 0xFF);
  136. }
  137. break;
  138. default:
  139. return emptyByte;
  140. }
  141. } catch (NumberFormatException e) {
  142. return emptyByte;
  143. }
  144. return bytes;
  145. }
  146. public static String getHostIp() {
  147. try {
  148. return InetAddress.getLocalHost().getHostAddress();
  149. } catch (UnknownHostException e) {
  150. log.error(e.getMessage(), e);
  151. }
  152. return "127.0.0.1";
  153. }
  154. public static String getHostName() {
  155. try {
  156. return InetAddress.getLocalHost().getHostName();
  157. } catch (UnknownHostException e) {
  158. log.error(e.getMessage(), e);
  159. }
  160. return "未知";
  161. }
  162. }

 

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号