Tuesday 21 January 2014

Aide Memoire - Java, Unix and Host Names

I can't precisely remember why I needed to know this, but I'm sure it'll be useful some day.

Here's a Java class: -

import java.net.InetAddress;
import java.net.UnknownHostException;

public class hostStuff
{
public static void main(String[] args)
{

try
{
InetAddress address = InetAddress.getLocalHost();
System.out.println("My IP address ( via InetAddress.getLocalHost() ) is " + address.toString());

System.out.println("My hostname ( via InetAddress.GetHostName() ) is " + address.getHostName());
}
catch (UnknownHostException e)
{
       System.out.println("I'm sorry. I don't know my own name.");
}

try
{
byte[] ipAddr = new byte[] { 127, 0, 0, 1 };
InetAddress addr = InetAddress.getByAddress(ipAddr);
String hostnameCanonical = addr.getCanonicalHostName();

System.out.println("My canonical hostname ( via InetAddress.getByAddress() and InetAddress.getCanonicalHostName() ) is " + hostnameCanonical);
}
catch (UnknownHostException e)
{
System.out.println("I'm sorry, I don't even know my own name.");
}
}
}


and here's what it returns ( on my Mac ) : -

$ java hostStuff
My IP address ( via InetAddress.getLocalHost() ) is DMHMBP.local/192.168.1.70
My hostname ( via InetAddress.GetHostName() ) is DMHMBP.local
My canonical hostname ( via InetAddress.getByAddress() and InetAddress.getCanonicalHostName() ) is localhost

and here's what it returns ( on Red Hat Enterprise Linux ): -

$ java hostStuff
My IP address ( via InetAddress.getLocalHost() ) is rhel6.uk.ibm.com/127.0.0.1
My hostname ( via InetAddress.GetHostName() ) is rhel6.uk.ibm.com
My canonical hostname ( via InetAddress.getByAddress() and InetAddress.getCanonicalHostName() ) is localhost

I suspect I was trying to find out the difference between a hostname and a canonical hostname, as returned by different Java methods.

Nice, eh ?

No comments:

Visual Studio Code - Wow 🙀

Why did I not know that I can merely hit [cmd] [p]  to bring up a search box allowing me to search my project e.g. a repo cloned from GitHub...