1

I need to know the name of the current computer.

The simplest method is by running:

java.net.InetAddress.getLocalHost().getHostName()

With OpenJDK 7 in a Linux machine, the result is correct, as reported by the system command hostname.

But with OpenJDK 8, the returned name is localhost, which is useless.

Why the different behavior? How can I get the real name with Java 8?

Related questions:

Community
  • 1
  • 1
david.perez
  • 6,090
  • 4
  • 34
  • 57

2 Answers2

0

Try using getCanonicalHostName() rather than getHostName()!

JuanMoreno
  • 2,498
  • 1
  • 25
  • 34
Mick Francis
  • 139
  • 6
-1

My /etc/hosts file is like this:

127.0.0.1           localhost localhost.localdomain localhost4 localhost4.localdomain4 myserver

then:

InetAddress.getLocalHost().getHostName().equals("localhost")

If I change it to this:

127.0.0.1           myserver localhost localhost.localdomain localhost4 localhost4.localdomain4

then:

InetAddress.getLocalHost().getHostName().equals("myserver")

Java 8 is more sensitive to ordering than Java 7, which returns always right result.

UPDATE: Further investigation has shown that with CentOS 6, this is the behavior: Java 8 is ordering-dependent. In CentOS 7, Java 8 works like Java 7.

david.perez
  • 6,090
  • 4
  • 34
  • 57