Getting hostname with java fails in latest jdk7

前端 未结 4 1691
别那么骄傲
别那么骄傲 2021-02-14 07:43

I\'ve been getting hostname of the machine as follows:

InetAddress.getLocalHost().getHostName();

However, when I put latest JDK (jdk1.7.0_04),

4条回答
  •  忘掉有多难
    2021-02-14 07:51

    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.)

    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.

    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 execing another program.

    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.

提交回复
热议问题