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和主机名对应关系写清楚。