Java获取hostname代码

来源:互联网 发布:棉花云数据 编辑:程序博客网 时间:2024/06/03 13:35

Java获取hostname代码

支持Windows和Linux:


public static String getHostNameForLiunx() {try {return (InetAddress.getLocalHost()).getHostName();} catch (UnknownHostException uhe) {String host = uhe.getMessage(); // host = "hostname: hostname"if (host != null) {int colon = host.indexOf(':');if (colon > 0) {return host.substring(0, colon);}}return "UnknownHost";}}public static String getHostName() {if (System.getenv("COMPUTERNAME") != null) {return System.getenv("COMPUTERNAME");} else {return getHostNameForLiunx();}}



如果不想再catch中写获取hostname逻辑,可以编写/etc/hosts,把本机IP和主机名对应关系写清楚。

0 0