首页 > 作文

Java如何获取主机的基本信息详解

更新时间:2023-04-04 07:15:03 阅读: 评论:0

目录
1. 获取基本信息1.1 获取主机名称和系统1.2 获取用户信息1.3 获取主机ip等信息2. 获取cpu信息2.1 获取cpu核数3. 获取内存信息3.1 获取主机内存3.2 获取jvm内存4. 获取磁盘信息5. 获取java环境信息总结

最近在做一个主机资源监控的需求,首先是获取一些最简单的基本参,像一些主机名称、系统类型、ip、cpu、内存和磁盘等等这些数据,看起来虽然很简单,java的基本库就能完成,但是真的去使用的时候,还是有一些坑的。记录一下,已备后用。

1. 获取基本信息

1.1 获取主机名称和系统

主机名称可以通过网络类inetaddress来获取,主机系统和用户可以通过system类进行获取。

 public static void getloca当兵政审lhost(){     try{         inetaddress ip = inetaddress.getlocalhost();         string localname = ip.gethostname();         string osname = system.getproperty("os.name");         string urname = system.getproperty("ur.name");         string osversion = system.getproperty("os.version");         string osarch = system.getproperty("os.arch");                  system.out.println("当前用户:" + urname);         system.out.println("用户的主目录:"+props.getproperty("ur.home"));         system.out.println("用户的当前工作目录:"+props.getproperty("ur.dir"));         system.out.println("主机名称:" + localname);         system.out.println("主机系统:" + osname);         system.out.println("系统版本:" + osversion);         system.out.println("系统架构:" + osarch);     } catch (exception e) {         e.printstacktrace();     } }

1.2 获取用户信息

用户信息都是使用system类进行获取。

 public static void geturinfo(){     try{         string urname = system.getproperty("ur.name");         string urhome = system.getproperty("ur.home");         string urdir = system.getproperty("ur.dir");                  system.out.println("当前用户:" + urname);         system.out.println("用户主目录:"+ urhome);         system.out.println("当前工作目录:"+ urdir);     } catch (exception e) {         e.printstacktrace();     } }

1.3 获取主机ip等信息

主机的ip可以通过网络类inetaddress进行获取,但是这个方法很玄学,机器上多网卡还有虚拟机时,获取到就不准确了。目前做的获取的方法是痛殴便利网卡来获取ip。因为遍历网卡来获取ip要过滤一些不重要的网卡,过滤的方法是来自“经验”的笨方法,可以借鉴,但不保证日后网卡条件复杂的情况下获取不准确。测试的是linux、mac和windows系统可用。因为过滤条件不一样,所以分为windows获取和非windows获取。

windows系统获取ip:

 public static void getwindowsipandmac(){     try {         enumeration<networkinterface> allnetinterfaces = networkinterface.getnetworkinterfaces();         // 遍历网卡接口         while (allnetinterfaces.hasmoreelements()) {             networkinterface netinterface = allnetinterfaces.nextelement();             // 去除回环接口,子接口,未运行和接口             if (netinterface.isloopback() || netinterface.isvirtual() || !netinterface.isup()) {                 continue;             }                          // 重点来了:“经验”之谈             // 为了过滤掉虚拟机的网卡,可以通过网卡名来进行基础过滤。windows主机ip对应的网卡名会包含下面三个:intel  无线、realtek  网线、ethernet  兼容xp系统             if (!netinterface.getdisplayname().contains("intel")                 && !netinterface.getdisplayname().contains("realtek")                 && !netinterface.getdisplayname().contains("ethernet")) {                 continue;             }                          string ip = "";             string mac = "";             string niname = "";             enumeration<inetaddress> address = netinterface.getinetaddress();             while (address.hasmoreelements()) {                 inetaddress ia = address.nextelement();                 // 去除本地回环地址,子接口,未运行和地址                 if (ia != null && !ia.isloopbackaddress() && ia.issitelocaladdress() && !ia.isanylocaladdress()) {                     // 判断是否是ip v4地址                     if (ia instanceof inet4address) {                         ip = ia.gethostaddress();                         // 获取mac地址                         mac = getmac(ia);                         niname = netinterface.getname();                         if (stringutils.isnotblank(ip) && stringutils.isnotblank(mac) && stringutils.isnotblank(niname)){                             system.out.println("当前网卡:"+niname);                             system.out.println("当前主机ip:"+ip);                             system.out.println("当前主机mac:"+mac);                             return;                         }                     }                 }             }         }     } catch (socketexception e) {         e.printstacktrace();     } }

非windows系统获取ip:

其实和windows获取的差不多,也是遍历网卡然后进行过滤,不过这个没有“经验”,不知道要过滤那些,所以用inetaddress进行获取,经测试这个在非windows上获取的还是准确的(可能我linux网卡单一)。不过为了获取当前的网卡用了一个更笨的方法,既然当前获取的ip是准确的,那就根据ip去获取网卡。不过目前没有找到这个方法,所以可以在遍历网卡时取出符合当前ip的网卡。(此方法在我这个需求里是可以的,不保证拿走就能用)。

 public static void getlinuxipandmac(agentmonitor agentmonitor){     try {         // 先获取ip         inetaddress iad = inetaddress.getlocalhost();         string localip = iad.gethostaddress(); ​         // 遍历网卡         enumeration<networkinterface> allnetinterfaces = networkinterface.getnetworkinterfaces();         while (allnetinterfaces.hasmoreelements()) {             networkinterface netinterface = allnetinterfaces.nextelement();             // 去除回环接口,子接口,未运行和接口             if (netinterface.isloopback() || netinterface.isvirtual() || !netinterface.isup()) {                 continue;             } ​             string ip = "";             string mac = "";             string niname = "";             enumeration<inetaddress> address = netinterface.getinetaddress();             while (address.hasmoreelements()) {                 inetaddress ia = address.nextelement();                 if (ia != null && !ia.isloopbackaddress() &am手机内存卡格式化p;& ia.issitelocaladdress() && !ia.isanylocaladdress()) {                     // 判断是否是ip v4地址且是否和已获取的ip一致                     if (ia instanceof inet4address && ia.gethostaddress().equals(localip)) {                         ip = ia.gethostaddress();                         // 获取mac地址                         mac = getmac(ia);                         niname = netinterface.getname();                         if (stringutils.isnotblank(ip) && stringutils.isnotblank(mac) && stringutils.isnotblank(niname)){                             system.out.println("当前网卡:"+niname);                             system.out.println("当前主机ip:"+ip);                             system.out.println("当前主机mac:"+mac);                             return;                         }                     }                 }             }         } ​     } catch (exception e) {         e.printstacktrace();     } }

获取mac地址

 public static string getmac(inetaddress ia){     try {         //获取网卡,获取地址         byte[] mac = networkinterface.getbyinetaddress(ia).gethardwareaddress();         stringbuffer sb = new stringbuffer();         if (mac != null && mac.length>0){             for(int i=0; i<mac.length; i++) {                 if(i!=0) {                     sb.append("-");                 }                 //字节转换为整数                 string str = integer.tohexstring(mac[i] & 0xff);                 if(str.length()==1) {                     sb.append("0").append(str);                 }el {                     sb.append(str);                 }             }         }         return sb.tostring().toupperca();     } catch (socketexception e) {         e.printstacktrace();         return null;     } }

2. 获取cpu信息

获取cpu的信息这里选用的是oshi工具,经测试这个获取的还是比较准确的,而且该工具还可以获得其他硬件信息,能获取到的还是比较全面的。首先需要引入oshi的依赖。

 <dependency>     <groupid>com.github.oshi</groupid>     <artifactid>oshi-core</artifactid>     <version>3.12.2</version> </dependency>

oshi是依赖于jna,需要导入jna和jna-platform我这里用的oshi是3.12.2版本,对应使用的jna的版本是5.2.0。springboot项目是自带jna的,如果不是springboot项目需要额外导入。如果springboot项目自带的jna版本过低,也需要额外导入高版本的jna。

<dependency>

<groupid>net.java.dev.jna</groupid>

<artifactid>jna</artifactid>

<version>5.2.0</version>

</dependency>

jna版本信息

2.1 获取cpu核数

oshi中的centralprocessor进行获取。获取cpu物理可用的核数,如果有开启超频,那么获取的cpu核数可能会大于物理核数。

 public static void getcpucount(){     try {         // 获取systeminfo实例         systeminfo systeminfo = new systeminfo();         // 获取centralprocessor实例         centralprocessor processor = systeminfo.gethardware().getprocessor();         // 获取cpu核数         int cpucount = processor.getlogicalprocessorcount();         system.out.println("cpu核数:"+cpucount);     } catch (socketexception e) {         e.printstacktrace();     } }

2.2 获取cpu使用率

获取系统范围的cpu负载时,一共获取7个部分的负载。

cpu 空闲且系统没有未完成的磁盘 i/o 请求的时间。在系统有未完成的磁盘 i/o 请求期间一个或多个 cpu 空闲的时间。在windows不可用。在macos不可用。cpu 用于服务硬件 irq 的时间。在macos不可用。在具有良好优先级的用户级别执行时发生的 cpu 利用率。在windows不可用。cpu 用于服务软 irq 的时间。管理程序专用于系统中其他来宾的时间。在系统级别(内核)执行时发生的 cpu 利用率。在用户级别(应用程序)执行时发生的 cpu 使用率。

要使用此方法计算总体空闲时间,就要包括上面所有部分,这样计算出来的结果更准确且兼容各种平台。分两次获取上面信息,间隔1秒。这样就能计算出1秒的cpu各方面使用的差值,通过每一项的差值除以总量,便可以得到每一项的cpu使用率。

通过下面方法还可以获得cpu时间间隔内的使用率和总使用率。

 public static void getcpuinfo() {     try {         systeminfo systeminfo = new systeminfo();         centralprocessor processor = systeminfo.gethardware().getprocessor();         // 获取系统范围的cpu负载技计数         long[] prevticks = processor.getsystemcpuloadticks();         // 睡眠1s         timeunit.conds.sleep(1);         long[] ticks = processor.getsystemcpuloadticks();         // 具有良好优先级的用户级别         long nice = ticks[centralprocessor.ticktype.nice.getindex()] - prevticks[centralprocessor.ticktype.nice.getindex()];         // 硬件服务         long irq = ticks[centralprocessor.ticktype.irq.getindex()] - prevticks[centralprocessor.ticktype.irq.getindex()];         // 软服务使用         long softirq = ticks[centralprocessor.ticktype.softirq.getindex()] - prevticks[centralprocessor.ticktype.softirq.getindex()];         // 管理程序使用         long steal = ticks[centralprocessor.ticktype.steal.getindex()] - prevticks[centralprocessor.ticktype.steal.getindex()];         // 系统使用         long csys = ticks[centralprocessor.ticktype.system.getindex()] - prevticks[centralprocessor.ticktype.system.getindex()];         // 用户使用         long ur = ticks[centralprocessor.ticktype.ur.getindex()] - prevticks[centralprocessor.ticktype.ur.getindex()];         // 等待使用         long iowait = ticks[centralprocessor.ticktype.iowait.getindex()] - prevticks[centralprocessor.ticktype.iowait.getindex()];         // 空闲使用         long idle = ticks[centralprocessor.ticktype.idle.getindex()] - prevticks[centralprocessor.ticktype.idle.getindex()];         long totalcpu = ur + nice + csys + idle + iowait + irq + softirq + steal;         double sysrate = csys * 1.0 / totalcpu;         double urrate = ur * 1.0 / totalcpu;         double waitrate = csys * 1.0 / totalcpu;         double idlerate = csys * 1.0 / totalcpu;         double betweenrate = processor.getsystemcpuloadbetweenticks();         double cpuload = processor.getsystemcpuload();         system.out.println("cpu系统使用率:" + new decimalformat("#.##%").format(sysrate));         system.out.println("cpu用户使用率:" + new decimalformat("#.##%").format(urrate));         system.out.println("cpu当前等待率:" + new decimalformat("#.##%").format(waitrate));         system.out.println("cpu当前空闲率:" + new decimalformat("#.##%").format(idlerate));         // 获取cpu最近(时间间隔内)使用率         system.out.println("cpu load: "+ new decimalformat("#.##%").format(betweenrate) +"(counting ticks)");         // 获取cpu使用率         system.out.println("cpu load: "+ new decimalformat("#.##%").format(cpuload) +"(os mxbean)");     }catch (exception e){         e.printstacktrace();     } }

3. 获取内存信息

3.1 获取主机内存

获取内存信息可以使用operatingsystemmxbean 来获取。内存信息可以获取到的有内存总量和可用内存,通过这两个值在计算出内存已经使用的量和内存的使用率。获取内存信息同样也可以使用oshi包中的systeminfo类进行获取。但是测试时获取的数据没有operatingsystemmxbean获取的更精确。

 public static void getmeminfo(){     try {         operatingsystemmxbean osmxb = (operatingsystemmxbean) managementfactory.getoperatingsystemmxbean();         // 总内存,单位:字节             long total = osmxb.gettotalphysicalmemorysize();             // 空闲内存,单位:字节             long free = osmxb.getfreephysicalmemorysize();             // 可用内存,单位:字节             long usable = osmxb.getfreephysicalmemorysize();             // 已使用内存,单位:字节             long ud = total - free;             // 内存使用率             double urate = ud * 1.0 / total;             system.out.println("总共内存:" + new decimalformat("#.##").format(total*1.0 / math.pow(1024,3)) + "g");             system.out.println("空闲内存:" + new decimalformat("#.##").format(free*1.0 / math.pow(1024,3)) + "g");             system.out.println("已用内存:" + new decimalformat("#.##").format(ud*1.0 / math.pow(1024,3)) + "g");             system.out.println("可用内存:" + new decimalformat("#.##").format(usable*1.0 / math.pow(1024,3)) + "g");             system.out.println("内存使用率:" + new decimalformat("#.##%").format(urate * 100.0)); ​     }catch (exception e){         e.printstacktrace();     } }

3.2 获取jvm内存

获取jvm的内存信息需要使用memorymxbean接口中的memoryusage类。jvm信息主要是在系统运行时对jvm的使用情况。包括初始的内存大小、最大可用的内存以及当前已经使用的内存大小。

 public static void getjvmmeminfo(){     try {         memorymxbean memorymxbean = managementfactory.getmemorymxbean();         // 椎内存使用情况         memoryusage memoryusage = memorymxbean.getheapmemoryusage();         // jvm初始总内存,单位:字节         long inittotalmemorysize = memoryusage.getinit();         // jvm最大可用内存,单位:字节         long free = osmxb.getfreephysicalmemorysize();         // jvm已使用的内存,单位:字节         long usable = osmxb.getfreephysicalmemorysize();                  system.out.println("jvm初始总内存:" + new decimalformat("#.##").format(total*1.0 / math.pow(1024,3)) + "g");         sys个人缺点自我评价tem.out.println("jvm最大可用内存:" + new decimalformat("#.##").format(free*1.0 / math.pow(1024,3)) + "g");         system.out.println("jvm已使用的内存:" + new decimalformat("#.##").format(ud*1.0 / math.pow(1024,3)) + "g"); ​     }catch (exception e){         e.printstacktrace();     } }

4. 获取磁盘信息

获取磁盘的使用情况用的是基础的file类。首先是从根目录遍历所有磁盘信息,通过下面方法获取磁盘信息。

file.gettotalspace() :获取当前磁盘的总内存file.getfreespace() :获取当前磁盘的空闲内存file.getusablespace() :获取当前磁盘的可用内存

通过上面获取的三个参数,可以计算磁盘总的已使用内存和当前磁盘的内存使用率。

在计算每一个磁盘的信息时,通过全局变量统计所有磁盘的信息总和,然后计算出主机总的磁盘内存和使用率。

 /**  * @param radix 内存进制大小,"经验"之谈是:windows下进制是1024,mac和linux是1000  */ public static void getdiskinfo(int radix){     // 统计总内存     long total = 0;     // 统计总空闲     long free = 0;     // 统计总可用     long usable = 0;     // 统计总已用     long ud = 0;     // 磁盘总使用     double udrate = 0.0;     try{ ​         file[] disks = file.listroots();         for (file file : disks){             // 统计总量             total += file.gettotalspace();             free += file.getfreespace();             usable += file.getusablespace();             ud += file.gettotalspace() - file.getfreespace();                          string diskpath = file.getpath();             long disktotal = file.gettotalspace();             long diskfree = file.getfreespace();             long diskusable = file.getusablespace();             long diskud = disktotal - diskfree;             double diskudrate = diskud * 1.0 / disktotal;                       system.out.println("磁盘路径:" + diskpath);             system.out.println("总共空间:"+ new decimalformat("#.##").format(disktotal*1.0 / math.pow(radix,3)) + "g");             system.out.println("空闲空间:"+ new decimalformat("#.##").format(diskfree*1.0 / math.pow(radix,3)) + "g");             system.out.println("可用空间:"+ new decimalformat("#.##").format(diskusable*1.0 / math.pow(radix,3)) + "g");             system.out.println("已用空间:"+ new decimalformat("#.##").format(diskud*1.0 / math.pow(radix,3)) + "g");             system.out.println("空间使用率:" + new decimalformat("#.##%").format(diskudrate*100));                      }                  string rootpath = "/";         udrate = ud * 1.0 / total;                  system.out.println("磁盘根路径:"+ rootpath);         system.out.println("主机总共空间:"+ new decimalformat("#.##").format(total*1.0 / math.pow(radix,3)) + "g");         system.out.println("主机总空闲空间:"+ new decimalformat("#.##").format(free*1.0 / math.pow(radix,3)) + "g");         system.out.println("主机总可用空间:"+ new decimalformat("#.##").format(usable*1.0 / math.pow(radix,3)) + "g");         system.out.println("主机总已用空间:"+ new decimalformat("#.##").format(ud*1.0 / math.pow(radix,3)) + "g");         system.out.println("主机总使用率:" + new decimalformat("#.##%").format(udrate*100.0));              }catch (exception e){         e.printstacktrace();     } }

5. 获取java环境信息

这块就是补充说明了,暂时没用到,先保留一下,已备后用。

 public static void getjavainfo(){     properties props=system.getproperties();     system.out.println("java的运行环境版本:"+props.getproperty("java.version"));     system.out.println("java的运行环境供应商:"+props.getproperty("java.vendor"));     system.out.println("java供应商的url:"+props.getproperty("java.vendor.url"));     system.out.println("java的安装路径:"+props.getproperty("java.home"));     system.out.println("java的虚拟机规范版本:"+props.getproperty("java.vm.specification.version"));     system.out.println("java的虚拟机规范供应商:"+props.getproperty("java.vm.specification.vendor"));     system.out.println("java的虚拟机规范名称:"+props.getproperty("java.vm.specification.name"));     system.out.println("java的虚拟机实现版本:"+props.getproperty("java.vm.version"));     system.out.println("java的虚拟机实现供应商:"+props.getproperty("java.vm.vendor"));     system.out.println("java的虚拟机实现名称:"+props.getproperty("java.vm.name"));     system.out.println("java运行时环境规范版本:"+props.getproperty("java.specification.version"));     system.out.println("java运行时环境规范供应商:"+props.getproperty("java.specification.vender"));     system.out.println("java运行时环境规范名称:"+props.getproperty("java.specification.name"));     system.out.println("java的类格式版本号:"+props.getproperty("java.class.version"));     system.out.println("java的类路径:"+props.getproperty("java.class.path"));     system.out.println("加载库时搜索的路径列表:"+props.getproperty("java.library.path"));     system.out.println("默认的临时文件路径:"+props.getproperty("java.io.tmpdir"));     system.out.println("一个或多个扩展目录的路径:"+props.getproperty("java.ext.dirs")家长鼓励孩子的一段话);         system.out.println("文件分隔符:"+props.getproperty("file.parator"));//在 unix 系统中是"/" system.信息的传递out.println("路径分隔符:"+props.getproperty("path.parator"));//在 unix 系统中是":" system.out.println("行分隔符:"+props.getproperty("line.parator"));//在 unix 系统中是"/n" system.out.println("用户的账户名称:"+props.getproperty("ur.name }

总结

到此这篇关于java如何获取主机的基本信息的文章就介绍到这了,更多相关java获取主机信息内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

本文发布于:2023-04-04 07:15:01,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/e1ab40ba57f37cc4cee0b50372419ced.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:Java如何获取主机的基本信息详解.doc

本文 PDF 下载地址:Java如何获取主机的基本信息详解.pdf

标签:内存   主机   使用率   磁盘
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图