1

I posted a question about a problem that concerns inetaddress in java 8 : InetAddress java 8 is not getting the hostname

however I found a simple solution by using System.getenv("HOSTNAME") instead of InetAddress.getLocalHost().getHostName()...

I want to know what is the difference between getting the hostname using :

InetAddress.getLocalHost().getHostName();

or

System.getenv("HOSTNAME")

and is there any impacts? which is better?

Community
  • 1
  • 1
Mohamed Taboubi
  • 6,663
  • 11
  • 55
  • 87
  • You probably shouldn't rely on system environment variables – OneCricketeer Jul 28 '16 at 15:37
  • 1
    If you care about compatibility, know that `HOSTNAME` doesn't exist on Windows. But the main question is: Why do you need it? A machine can host many domains, so what is it you need the name for? – Andreas Jul 28 '16 at 15:37
  • Not just Windows but there is no guarantee it will be set on Linux. First, it is not a POSIX required environment variable and some distro may choose not to use it or to stop using it. Second, depending on how the process is launched it doesn't necessarily have all environment variables exported forwards. – Pace Jul 28 '16 at 15:40
  • Seems like you should read this answer, and others in this post. http://stackoverflow.com/a/15197702/2308683 – OneCricketeer Jul 28 '16 at 15:41

2 Answers2

0

In most systems, they should return the same value. However, System.getenv() relies on the system's environment variables.

0

System.getenv("HOSTNAME") is the best one for you, because this will give the exact value that you expected as it is coming from an Environment Variable.

InetAddress.getLocalHost().getHostName() It will give host name that can be known under many different hostnames. Read more Recommended way to get hostname in Java

Community
  • 1
  • 1