下面哪一种方法是在Java中获得当前计算机主机名的最佳和最可移植的方法?
Runtime.getRuntime().exec(“hostname”)
vs
InetAddress.getLocalHost().getHostName()
下面哪一种方法是在Java中获得当前计算机主机名的最佳和最可移植的方法?
Runtime.getRuntime().exec(“hostname”)
vs
InetAddress.getLocalHost().getHostName()
当前回答
InetAddress.getLocalHost(). gethostname()是两者中最好的方法,因为这是开发人员级别的最佳抽象。
其他回答
InetAddress.getLocalHost(). gethostname()是两者中最好的方法,因为这是开发人员级别的最佳抽象。
只有一句话……跨平台(Windows-Linux-Unix-Mac(Unix))[始终工作,不需要DNS]:
String hostname = new BufferedReader(
new InputStreamReader(Runtime.getRuntime().exec("hostname").getInputStream()))
.readLine();
你完蛋了!!
如果您不反对使用来自maven中心的外部依赖,我编写了gethostname4j来为自己解决这个问题。它只是使用JNA来调用libc的gethostname函数(或在Windows上获取ComputerName)并将其作为字符串返回给您。
https://github.com/mattsheppard/gethostname4j
InetAddress.getLocalHost(). gethostname()是更可移植的方式。
Exec(“hostname”)实际上调用操作系统来执行hostname命令。
以下是关于SO的一些其他相关答案:
Java当前机器名和登录用户? 获取本地机器的DNS名称,就像远程机器看到的那样
编辑:你应该看看A.H.的回答,或者Arnout Engelen的回答,详细说明为什么这可能不会像预期的那样工作,这取决于你的情况。作为对这个特别要求可移植的人的回答,我仍然认为getHostName()很好,但它们提出了一些值得考虑的优点。
hostName == null;
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
{
while (interfaces.hasMoreElements()) {
NetworkInterface nic = interfaces.nextElement();
Enumeration<InetAddress> addresses = nic.getInetAddresses();
while (hostName == null && addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (!address.isLoopbackAddress()) {
hostName = address.getHostName();
}
}
}
}