简体   繁体   中英

Getting ip address instead of hostname from gethostbyname function from InetAddress class of java

How is it possible to get the IP-Address from the gethostbyname function from the InetAddress class in java ? With the following code I am not getting the hostname from the local machine's ip adrress.

import java.net.InetAddress;

class GetHost{

    public static void main(String args[])throws Exception{

        String hostIp=args[0];
        InetAddress addr = InetAddress.getByName(hostIp);
        String host = addr.getHostName();
        if(host.endsWith(".local"))
        {
            int lenght=host.length() ;
            System.out.print(""+host.substring(0,lenght-6));

        }
        else
            System.out.print(host);

    }
 }
private InetAddress getIP() throws SocketException {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        NetworkInterface ni;
        while (nis.hasMoreElements()) {
            ni = nis.nextElement();
            if (!ni.isLoopback() && ni.isUp()) {
                for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
                    if (ia.getAddress().getAddress().length == 4) {
                        return ia.getAddress();
                    }
                }
            }
        }
        return null;
    }

This code returns the local ip address of the pc. A simple change to getHostName should work.

Do you have the hosts file with a line like this?

127.0.0.1 localhost

In your code getByName will return an InetAddress with the IP address but no hostname. When you call getHostName it will try to get the host name within the InetAddress object, and if it does not exist, the function carries out a reverse lookup address.

http://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html#getHostName()

If your hosts file is not updated with the IP you are passing a reverse DNS query will be sent out. I assume there is no DNS server with the name and address of your host, so you need to have th hosts file updated. In linux, it is in /etc/hosts. In Windows, it is located in C:\\Windows\\System32\\drivers\\etc

BTW, you can also use:

InetAddress.getLocalHost()

But you will have the same problem without the proper entry in hosts file.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM