下面哪一种方法是在Java中获得当前计算机主机名的最佳和最可移植的方法?

Runtime.getRuntime().exec(“hostname”)

vs

InetAddress.getLocalHost().getHostName()


当前回答

环境变量也可以提供有用的方法——Windows上的COMPUTERNAME,大多数现代Unix/Linux shell上的HOSTNAME。

参见:https://stackoverflow.com/a/17956000/768795

我使用这些作为InetAddress.getLocalHost(). gethostname()的“补充”方法,因为正如一些人指出的那样,该函数不能在所有环境中工作。

Runtime.getRuntime().exec("hostname")是另一个可能的补充。在这个阶段,我还没有用过它。

import java.net.InetAddress;
import java.net.UnknownHostException;

// try InetAddress.LocalHost first;
//      NOTE -- InetAddress.getLocalHost().getHostName() will not work in certain environments.
try {
    String result = InetAddress.getLocalHost().getHostName();
    if (StringUtils.isNotEmpty( result))
        return result;
} catch (UnknownHostException e) {
    // failed;  try alternate means.
}

// try environment properties.
//      
String host = System.getenv("COMPUTERNAME");
if (host != null)
    return host;
host = System.getenv("HOSTNAME");
if (host != null)
    return host;

// undetermined.
return null;

其他回答

在Java中获取当前计算机主机名的最方便的方法如下:

import java.net.InetAddress;
import java.net.UnknownHostException;

public class getHostName {

    public static void main(String[] args) throws UnknownHostException {
        InetAddress iAddress = InetAddress.getLocalHost();
        String hostName = iAddress.getHostName();
        //To get  the Canonical host name
        String canonicalHostName = iAddress.getCanonicalHostName();

        System.out.println("HostName:" + hostName);
        System.out.println("Canonical Host Name:" + canonicalHostName);
    }
}

基于Dan Ortega的回答,我创建了一个通用的executeCommand(String)方法,它接受命令作为参数。

import java.io.*;

public class SystemUtil {
  public static void main(String[] args) throws IOException {
    System.out.println(retrieveHostName());
  }
     
  public static String retrieveHostName() throws IOException {
    return executeCommand("hostname");
  }
     
  private static String executeCommand(String command) throws IOException {
    return new BufferedReader(
        new InputStreamReader(Runtime.getRuntime().exec(command).getInputStream()))
      .readLine();
  }
}

InetAddress.getLocalHost().getHostName()是更好的(由Nick解释),但仍然不是很好

一个主机可以使用许多不同的主机名。通常,您将在特定的上下文中查找主机名。

例如,在web应用程序中,您可能要查找发出您当前正在处理的请求的人所使用的主机名。如何最好地找到它取决于你的web应用程序使用的框架。

在其他一些面向互联网的服务中,你会希望你的服务从“外部”可用的主机名。由于代理、防火墙等原因,这甚至可能不是安装服务的机器上的主机名——你可能会尝试提出一个合理的默认值,但你一定要让安装它的人都可以配置它。

只有一句话……跨平台(Windows-Linux-Unix-Mac(Unix))[始终工作,不需要DNS]:

String hostname = new BufferedReader(
    new InputStreamReader(Runtime.getRuntime().exec("hostname").getInputStream()))
   .readLine();

你完蛋了!!

InetAddress.getLocalHost(). gethostname()是两者中最好的方法,因为这是开发人员级别的最佳抽象。