支持Windows和Linux,可以处理自动Linuxi下诡异的UnknownHostException错误。
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和主机名对于关系写清楚,就不会有UnknownHostException。
参考:
https://forums.oracle.com/forums/thread.jspa?threadID=1689521&tstart=240
--heipark