这个问题很老了,但不幸的是仍然相关,因为在Java中获取机器的主机名仍然不容易。以下是我在不同系统上进行一些测试运行的解决方案:
public static void main(String[] args) throws IOException {
String OS = System.getProperty("os.name").toLowerCase();
if (OS.indexOf("win") >= 0) {
System.out.println("Windows computer name throguh env:\"" + System.getenv("COMPUTERNAME") + "\"");
System.out.println("Windows computer name through exec:\"" + execReadToString("hostname") + "\"");
} else {
if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0) {
System.out.println("Linux computer name throguh env:\"" + System.getenv("HOSTNAME") + "\"");
System.out.println("Linux computer name through exec:\"" + execReadToString("hostname") + "\"");
System.out.println("Linux computer name through /etc/hostname:\"" + execReadToString("cat /etc/hostname") + "\"");
}
}
}
public static String execReadToString(String execCommand) throws IOException {
Process proc = Runtime.getRuntime().exec(execCommand);
try (InputStream stream = proc.getInputStream()) {
try (Scanner s = new Scanner(stream).useDelimiter("\\A")) {
return s.hasNext() ? s.next() : "";
}
}
}
不同操作系统的结果:
开放使用 13.1
Linux computer name throguh env:"machinename"
Linux computer name through exec:"machinename
"
Linux computer name through /etc/hostname:""
Ubuntu 14.04 LTS这个有点奇怪,因为返回正确的主机名,但不会(然而,这可能只是我的环境的问题):echo $HOSTNAME
System.getenv("HOSTNAME")
Linux computer name throguh env:"null"
Linux computer name through exec:"machinename
"
Linux computer name through /etc/hostname:"machinename
"
视窗 7
Windows computer name throguh env:"MACHINENAME"
Windows computer name through exec:"machinename
"
机器名称已被替换为(一些)匿名化,但我保留了大写和结构。请注意,在执行 时需要注意额外的换行符,在某些情况下,您可能需要考虑它。hostname