Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How does java.net.InetAddress.getCanonicalHostName() work?

Status
Not open for further replies.

cpjust

Programmer
Sep 23, 2003
2,132
0
0
US
Hi,
I need to get the machine name that my java code is running on. I wrote this to test a couple functions that look promising:

Code:
public static void main( String[] args ) throws IOException
{
	InetAddress addr = InetAddress.getLocalHost();
	System.out.println( addr.getHostName() );
	System.out.println( addr.getHostAddress() );
	System.out.println( addr.getCanonicalHostName() );
}

but when I run it, I get:
MyMachineName
127.0.1.1
MyMachineName


I looked in my /etc/hosts file and saw that 127.0.1.1 was the 2nd line after 127.0.0.1

Do those functions just look in /etc/hosts or in /etc/hostname or do they use some other way of determining the Host Name? I just want to make sure my code doesn't stop working if it's run on a machine that has nothing but the 127.0.0.1 localhost in the /etc/hosts file...

Also, how can I get my real IP Address rather than my loopback address?
 
The localhost could be run on its own device. To get to it, and to all the others in the process commenting out some breaks, enumerate the NetworkInterface is the surer way. Like this (importing java.net.NetworkInterface as well).
[tt]
public static void main(String[] args) throws Exception {
InetAddress inetaddr_lh=null;
Enumeration<NetworkInterface> enet=NetworkInterface.getNetworkInterfaces();
while (enet.hasMoreElements()) {
NetworkInterface inet=enet.nextElement();
Enumeration<InetAddress> einetaddr=inet.getInetAddresses();
if (einetaddr.hasMoreElements()) {
InetAddress inetaddr=einetaddr.nextElement();
//System.out.println(inetaddr.getHostName());
//System.out.println(inetaddr.getHostAddress());
//System.out.println(inetaddr.getCanonicalHostName());
//System.out.println(inetaddr.isLoopbackAddress());
if (inetaddr.isLoopbackAddress()) {
inetaddr_lh=InetAddress.getByName(inetaddr.getHostName());
break;
}
}
if (inetaddr_lh != null) break;
}
if (inetaddr_lh != null) {
System.out.println("localhost:");
System.out.println(inetaddr_lh.getHostName());
System.out.println(inetaddr_lh.getHostAddress());
System.out.println(inetaddr_lh.getCanonicalHostName());
} else {
System.out.println("Cannot find Loopback address.");
}
}
[/tt]
 
Thanks, that gave me an idea of how to get the machine name:
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() ) )
					continue;
				else
				{
					name = inet.getCanonicalHostName();
					break;
				}
			}
		}

		return name;
	}
But that just gives me the name of my VMWare interface rather than my real computer name.
When I use InetAddress.getLocalHost().getCanonicalHostName() it returns the correct name. I'm just wondering if it will always return the correct name or if it depends on what's in my /etc/hosts file or something?
 
I may be picky but, this code:
Code:
if ( inet.getCanonicalHostName().equalsIgnoreCase( inet.getHostAddress() ) )
    continue;
else
{
    name = inet.getCanonicalHostName();
    break;
}
reads just like Cobol, shouldn't you be coding like:
Code:
if ( !inet.getCanonicalHostName().equalsIgnoreCase( inet.getHostAddress() ) )
{
    name = inet.getCanonicalHostName();
    break;
}
(Code what you mean and mean what you code...)

HTH
TonHu
 
Yes, I usually do that, but I was trying some different things and didn't clean it up before I posted it.
 
I found another way to get the hostname that might work better - using the System.getenv() function:
Code:
System.out.println( "HOSTNAME = " + System.getenv( "HOSTNAME" ) );
But this prints out:
HOSTNAME = null

When I type set on the command line I see HOSTNAME, but when I type env I don't see it.
I tried this, which does print out properly:
Code:
System.out.println( "USERNAME = " + System.getenv( "USERNAME" ) );

Does System.getenv() only work on variables that you can see in the with the set command on Linux?
 
amendment
Just want correct the line I posted, the if is meant to be while! (that's why I'd put double breaks). Sorry to bother the forum.
>[self]if (einetaddr.hasMoreElements()) {
[tt][red]while[/red] (einetaddr.hasMoreElements()) {[/tt]
 
I look up the documentation and .getenv() null parameter returns an abstract Map<String,String>. Hence, the natural progression of the logic would be this. This will allow you to see all the environment variables. I think "hostname", well, it is not on mine.
[tt]
HashMap<String, String> menv = new HashMap<String, String>();
menv.putAll(System.getenv());
System.out.println("Entries: key=value");
for (Iterator<Map.Entry<String, String>> iter=menv.entrySet().iterator(); iter.hasNext();) {
Map.Entry<String, String> entry = iter.next();
System.out.println(entry.getKey() + "=" + entry.getValue());
}
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top