How do I get the Hostname in Java?

This is a discussion on How do I get the Hostname in Java? within the Tech Board forums, part of the Community Boards category; I'm trying to find the best way of getting the system's Hostname in Java. I haven't found a function specifically ...

  1. #1
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545

    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:
    Code:
    System.out.println( "HOSTNAME = " + System.getenv( "HOSTNAME" ) );
    But for some reason it prints "HOSTNAME = null".

    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:
    Code:
    	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() )
    				continue;
    
    			Enumeration<InetAddress> eaddr = net.getInetAddresses();
    
    			while ( eaddr.hasMoreElements() )
    			{
    				InetAddress inet = eaddr.nextElement();
    
    				if ( inet.getCanonicalHostName().equalsIgnoreCase( inet.getHostAddress() ) == false )
    				{
    					name = inet.getCanonicalHostName();
    					break;
    				}
    			}
    		}
    
    		return name;
    	}
    Any ideas of how to reliably get the hostname in Java?
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  2. #2
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Here's another not so portable way that seems to work, but I'm not a big fan of non-portable solutions:
    Code:
    Runtime run = Runtime.getRuntime();
    Process proc = run.exec( "hostname" );
    BufferedInputStream in = new BufferedInputStream( proc.getInputStream() );
    byte [] b = new byte[256];
    System.out.println( new String( b ) );
    BTW, does the 'hostname' program exist on every UNIX system or is it sometimes not installed on some systems?
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  3. #3
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    Running hostname on my Mac:
    Code:
    dinos-computer:MyApplets dino hostname
    dinos-computer.local
    dinos-computer:MyApplets dino $
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

  4. #4
    Code Abuser
    Join Date
    Jan 2009
    Posts
    16
    This seems to run fine on my Mac.
    Code:
    class PrintHostname
    {
      public static void main(String args[]) throws java.net.UnknownHostException
      {
        java.net.InetAddress addr = java.net.InetAddress.getLocalHost();
        String hostname = addr.getHostName();
        System.out.println("Hostname of system = " + hostname);
      }
    }
    results:
    Code:
    kitty:~ $ javac PrintHostname.java
    kitty:~ $ java PrintHostname
    Hostname of system = kitty
    kitty:~ $
    >BTW, does the 'hostname' program exist on every UNIX system
    To my knowledge, yes.

  5. #5
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Yes, that seems to run fine on my system too, but does that mean it will work on all systems?
    I'm worried that it might not always return the correct name on machines with multiple Network Interfaces...

    I'm wondering what Java means by "LocalHost"? To me that sounds like the loopback address, but it can't be, since it's returning the real hostname rather than "localhost".
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  6. #6
    and the hat of copycat stevesmithx's Avatar
    Join Date
    Sep 2007
    Posts
    504
    Quote Originally Posted by cpjust View Post
    Yes, that seems to run fine on my system too, but does that mean it will work on all systems?
    I'm worried that it might not always return the correct name on machines with multiple Network Interfaces...

    I'm wondering what Java means by "LocalHost"? To me that sounds like the loopback address, but it can't be, since it's returning the real hostname rather than "localhost".
    I think localhost means the loopback address 127.0.0.1 which gets resolved to the hostname which when invoked by getHostName() method.
    Not everything that can be counted counts, and not everything that counts can be counted
    - Albert Einstein.


    No programming language is perfect. There is not even a single best language; there are only languages well suited or perhaps poorly suited for particular purposes.
    - Herbert Mayer

  7. #7
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    How do you define the "real" hostname? What about my machine that is in two networks with two different names, both being equal? What's its "real" hostname?

    Your endeavor is doomed.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  8. #8
    Code Abuser
    Join Date
    Jan 2009
    Posts
    16
    Wait, are we talking about the same thing here? From my understanding, by 'hostname' cpjust was referring to the name of the machine, not the DNS name that other machines use to refer to the machine. The Single Unix Specification only allows one hostname (or rather, POSIX) and I'm pretty sure all the Unix-derivatives are the same.

    For example:
    http://opengroup.org/onlinepubs/0079...thostname.html

    The Unix utility 'hostname' when run without any arguments actually calls gethostname().

    As for the code snippet I posted, I can't vouch for the correctness of that. I based it off some other code I found online and really don't know if that's the 'correct' way to do it.
    Last edited by sorrofix; 02-07-2009 at 01:35 PM.

  9. #9
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    So either execute hostname and capture the output (if POSIX defines it, it's as portable as you're going to get) or JNI-wrap gethostname(). Or find a POSIX system interface Java library - Googling for "java posix" yields a lot of stuff.
    http://basepath.com/aup/jtux/
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  10. #10
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    You know, I may be pursuing an untamed ornithoid without cause (Star Trek humor), so maybe I'll just use this:
    Code:
    java.net.InetAddress.getLocalHost().getHostName();
    and if I actually run into any problems with that code, then I'll worry about using some other method.
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C#, Java, C++
    By incognito in forum A Brief History of Cprogramming.com
    Replies: 10
    Last Post: 10-05-2004, 03:06 PM
  2. First Java Class at college
    By GanglyLamb in forum A Brief History of Cprogramming.com
    Replies: 24
    Last Post: 09-29-2004, 11:38 PM
  3. The Java language is being expanded
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 26
    Last Post: 06-11-2004, 10:07 PM
  4. Java woes
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 07-06-2003, 01:37 AM
  5. How to use Java with C++
    By Arrow Mk 84 in forum C++ Programming
    Replies: 2
    Last Post: 02-27-2003, 04:12 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21