I’ve been getting hostname of the machine as follows:
InetAddress.getLocalHost().getHostName();
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
It’s been returning REDBULL until upgrade. So I changed that around putting
127.0.0.1 redbull localhost
instead and it started returning REDBULL without a problem.
Is there a better way of making this work?
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/hostnameon Unix machines or look at the environment variableCOMPUTERNAMEon Windows. It’s sort of a judgement call as to whether you feel better calling JNI orexecing 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, wheregethostname()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 ofcustomer-10-42-21-42or 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.