Friday, April 1, 2011

Order of reference in /etc/host

The application retrieve the host name from the JVM with a java-system-method (GetHostName).


Server1:/opt/lee/bin$ cat GetHostName.java
import java.net.*;
import java.io.*;

public class GetHostName{
public static void main(String [] args) {
   try {
        InetAddress addr = InetAddress.getLocalHost();
        byte[] ipAddr = addr.getAddress();
        String hostname = addr.getHostName();
    System.out.println("hostname="+hostname);
    } catch (UnknownHostException e) {
    }

    }
}


When this is run on two different machines, it produces different results.

Server1:/opt/lee/bin$ /opt/lee/1.4.2/bin/java GetHostName
hostname=Server1.xyz.MySite.com


Server2:/opt/lee/bin$ /opt/lee/1.4.2/bin/java GetHostName
hostname=Server2


The application requires the result to be hostname=Server1 and not the FQDN (Server1.xyz.MySite.com)

Why?

The OS hostnames are same and has no differences

Server1:/root# hostname
Server1
Server1:/root#

Server2:/root# hostname
Server2
Server2:/root
#

Server1.xyz.MySite.com is the FQDN of the host Server1.

This is caused by difference in /etc/hosts files on both machines.

Server1:/root# cat /etc/hosts
#
# Internet host table
#
127.0.0.1       localhost
10.3.100.40     Server1.xyz.MySite.com loghost Server1

Server2:/root# cat /etc/hosts
#
# Internet host table
#
127.0.0.1       localhost
10.3.100.30     Server2 Server2.xyz.MySite.com loghost


The order in which the names are specified makes the difference. The search happens from left to right. So the first token is picked up which is
Server1.xyz.MySite.com on the host Server1.

Change the order in /etc/hosts file.

Server2:/root# vi /etc/hosts
"/etc/hosts" [Read only] 5 lines, 131 characters
#
# Internet host table
#
127.0.0.1       localhost
10.3.100.40     Server1 Server1.xyz.MySite.com loghost
~
~
~
~
~
"/etc/hosts" 5 lines, 118 characters
Server2:/root#

No comments:

Post a Comment