I\'ve been getting hostname of the machine as follows:
InetAddress.getLocalHost().getHostName();
However, when I put latest JDK (jdk1.7.0_04),
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 exec
ing 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.
I had the same problem and when all the following lined up it worked. host name had to be appended with DOT local
$ scutil --get HostName
drums
$ scutil --get LocalHostName
drums
$ scutil --get ComputerName
drums
$ sudo hostname drums.local
$ hostname
drums.local
$sudo vim /etc/hosts
192.168.x.IP drums
127.0.0.1 localhost drums
255.255.255.255 broadcasthost
::1 localhost
fXXX::1XXX localhost
$networksetup -setv6off Ethernet
$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.9
$ java -version
java version "1.7.0_45"
Java(TM) SE Runtime Environment (build 1.7.0_45-b18)
Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)
If you're not against using an external dependency from maven central, I wrote gethostname4j to solve this problem for myself. It just uses JNA to call libc's gethostname function (or gets the ComputerName on Windows) and returns it to you as a string.
https://github.com/mattsheppard/gethostname4j
@edward-thomson's answer above makes me thing I might have a bit more work to do to make it work well on MacOS though :)
This is a known issue in the macosx port of JDK7u4.
http://java.net/jira/browse/MACOSX_PORT-564