Java Runtime.getRuntime()和getHostName()获取主机名方法及使用代码
时间:2022-08-22
1、通过Runtime.getRuntime().exec("hostname")获取主机名
Process hostname = Runtime.getRuntime().exec("hostname"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(hostname.getInputStream())); String s; while ((s = stdInput.readLine()) != null) { System.out.println(s); }
2、通过getHostName()方法获取主机名
import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Properties; import java.util.Set; public >TestSystemProperties { public static void main(String [] args){ InetAddress netAddress = getInetAddress(); System.out.println("host ip:" + getHostIp(netAddress)); System.out.println("host name:" + getHostName(netAddress)); Properties properties = System.getProperties(); Set<String> set = properties.stringPropertyNames(); //获取java虚拟机和系统的信息。 for(String name : set){ System.out.println(name + ":" + properties.getProperty(name)); } } public static InetAddress getInetAddress(){ try{ return InetAddress.getLocalHost(); }catch(UnknownHostException e){ System.out.println("unknown host!"); } return null; } public static String getHostIp(InetAddress netAddress){ if(null == netAddress){ return null; } String ip = netAddress.getHostAddress(); //get the ip address return ip; } public static String getHostName(InetAddress netAddress){ if(null == netAddress){ return null; } String name = netAddress.getHostName(); //get the host address return name; } }
特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。