InetAddress.getLocalHost () returns false if the host name is 64 characters

I am using below code to print hostname for linux using java 1.5

public static void main(String a[]) {
    System.out.println( InetAddress.getLocalHost().getCanonicalHostName() );
}

When I have the hostname of the system, the string length is 64 char, the code simply prints "localhost.localdomain". If the host name is less than 64, it displays the host name correctly. The maximum host name length for the system is 64 (getconf HOST_NAME_MAX gives 64)

What could be wrong here? Could this be a mistake (although, I tend to think that the problem is on my side)

Thanks for the help!

+5
source share
2 answers

Linux, , InetAddress.getLocalHost() loopback- ( 127/8, 127.0.0.1). , , /etc/hosts, , localhost.localdomain.

/, , IP-, (eth0 ), IPv4, loopback.

try {
    // Replace eth0 with your interface name
    NetworkInterface i = NetworkInterface.getByName("eth0");

    if (i != null) {

        Enumeration<InetAddress> iplist = i.getInetAddresses();

        InetAddress addr = null;

        while (iplist.hasMoreElements()) {
            InetAddress ad = iplist.nextElement();
            byte bs[] = ad.getAddress();
            if (bs.length == 4 && bs[0] != 127) {
                addr = ad;
                // You could also display the host name here, to 
                // see the whole list, and remove the break.
                break;
            }
        }

        if (addr != null) {
            System.out.println( addr.getCanonicalHostName() );
        }
    } catch (...) { ... }

, . .

, , @rafalmag

NetworkInterface.getByName( "eth0" ) NetworkInterface.getNetworkInterfaces()

+3

, , Java 6, , , , Java, , 64- .

0

All Articles