In the latest JDK7, using java failed hostname failed
I have got the host name of the machine as follows:
InetAddress.getLocalHost().getHostName();
However, when I install the latest JDK (jdk1.7.0_04), the above code simply returns localhost I checked / etc / hosts (its Linux) and said there:
127.0.0.1 localhost redbull
Always return redfull before upgrading So I changed that
127.0.0.1 redbull localhost
Instead, it starts returning redball without a problem
Is there a better way to do this work?
Solution
Well, I thought of marking this as DUP, but I found that the only answer is to suggest you use InetAddress getLocalHost(). getHostName(). Frankly, in this case, I think "localhost" should be returned I think these answers are correct, because there is really no pure Java way to do it (at least none can be transplanted back to the old JRE)
We use JNI to achieve this We call scpreferencesgethostname() elsewhere on Mac OS 10.4, scdynamicstorecopylocalhostname(), getcomputername(), gethostname() on old Mac OS, Win32
Of course, you can simply call / bin / hostname on a UNIX machine, or view the environment variable computername. On windows Whether you feel better calling JNI or executing another program is a judgment call
The reason why we don't call gethostname() on Mac OS is because MAC executes a strange dynamic hostname, where gethostname() returns the reverse DNS of the primary Ethernet device If I plug my Mac directly into my cable modem, I will get a customer's host name of 10-42-21-42, or my cable provider decides to set up my PTR record in its DNS Instead, going to preferences gives you a stable host name determined by the user