How do I get the Hostname in Java?
I'm trying to find the best way of getting the system's Hostname in Java.
I haven't found a function specifically for it, which is strange, I would have expected that would be common enough to be in there somewhere.
I tried this not so portable way to get it on UNIX:
But for some reason it prints "HOSTNAME = null".
System.out.println( "HOSTNAME = " + System.getenv( "HOSTNAME" ) );
I also tried this way which sort of works, except on my Linux desktop where it returns the vmnet8 adapter name instead of the real hostname:
Any ideas of how to reliably get the hostname in Java?
static String GetMachineName() throws SocketException
String name = null;
Enumeration<NetworkInterface> enet = NetworkInterface.getNetworkInterfaces();
while ( enet.hasMoreElements() && (name == null) )
NetworkInterface net = enet.nextElement();
if ( net.isLoopback() )
Enumeration<InetAddress> eaddr = net.getInetAddresses();
while ( eaddr.hasMoreElements() )
InetAddress inet = eaddr.nextElement();
if ( inet.getCanonicalHostName().equalsIgnoreCase( inet.getHostAddress() ) == false )
name = inet.getCanonicalHostName();