问题描述
我一直在获取机器的主机名如下:
I've been getting hostname of the machine as follows:
InetAddress.getLocalHost().getHostName();
但是,当我输入最新的JDK(jdk1.7.0_04)时,上面的代码只返回LOCALHOST。我检查了/ etc / hosts(它的linux),它说:
However, when I put latest JDK (jdk1.7.0_04), the code above simply return LOCALHOST. I checked /etc/hosts (its linux) and it says there:
127.0.0.1 localhost redbull
升级之前一直在返回REDBULL。所以我改变了这一点
It's been returning REDBULL until upgrade. So I changed that around putting
127.0.0.1 redbull localhost
相反,它开始返回REDBULL没有问题。
instead and it started returning REDBULL without a problem.
有没有更好的方法使这项工作?
Is there a better way of making this work?
推荐答案
好吧,我想把它标记为重复,但我发现的唯一答案建议您使用 InetAddress.getLocalHost()。的gethostname()
。坦率地说,在这种情况下,我认为应该返回localhost。我认为这些答案是正确的,因为实际上没有纯Java方法(至少没有一种可以移植到旧JRE中。)
Well, I thought about flagging this as a dup, but the only answers I find suggest that you use InetAddress.getLocalHost().getHostName()
. Which, frankly, I think should return "localhost" in this case. And those answers, I suppose, are correct, in that there's really no pure Java way of doing this (at least none that are portable back to older JREs.)
我们使用JNI来实现这一目标。我们在Mac OS 10.4 +上调用 SCPreferencesGetHostName()
,在旧Mac OS上调用 SCDynamicStoreCocalLocalHostName()
, Win32上的GetComputerName()
, gethostname()
其他地方。
We use JNI to accomplish this. We call SCPreferencesGetHostName()
on Mac OS 10.4+, SCDynamicStoreCopyLocalHostName()
on older Mac OS, GetComputerName()
on Win32, gethostname()
everywhere else.
你可以当然,只需在Unix机器上调用 / bin / hostname
,或者在Windows上查看环境变量 COMPUTERNAME
。这是一种判断调用,你是否觉得更好地调用JNI或 exec
另一个程序。
You could, of course, simply call /bin/hostname
on Unix machines or look at the environment variable COMPUTERNAME
on Windows. It's sort of a judgement call as to whether you feel better calling JNI or exec
ing another program.
对于什么它值得,我们在Mac OS上不调用 gethostname()
的原因是因为Mac做了一个奇怪的动态主机名,其中 gethostname()
将返回主以太网设备的反向DNS。如果我将我的Mac直接插入我的电缆调制解调器,我会得到一个主机名 customer-10-42-21-42
或我的有线电视提供商决定设置的任何内容作为我在他们的DNS中的PTR记录。相反,转到首选项会得到一个由用户确定的稳定主机名。
For what it's worth, the reason we don't call gethostname()
on Mac OS is because Mac does a weird dynamic hostname thing, where gethostname()
will return the reverse DNS of your primary ethernet device. If I were to plug my Mac straight into my cable modem, I'd get a hostname of customer-10-42-21-42
or whatever my cable provider decided to set as my PTR record in their DNS. Instead, going to the preferences will get you a stable hostname that was determined by the user.
这篇关于在最新的jdk7中,使用java获取主机名失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!