从InetAddress类的java中获取gethostbyname函数的ip地址而不是hostname

时间:2014-06-05 10:04:49

标签: java dns network-programming

如何从java中gethostbyname类的InetAddress函数中获取IP地址?使用以下代码,我无法从本地计算机的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);

    }
 }

2 个答案:

答案 0 :(得分:0)

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;
    }

此代码返回pc的本地IP地址。对getHostName的简单更改应该有效。

答案 1 :(得分:0)

你有一个像这样的行的主机文件吗?

127.0.0.1 localhost

在您的代码中,getByName将返回一个IP地址但没有主机名的InetAddress。当您调用getHostName时,它将尝试在InetAddress对象中获取主机名,如果它不存在,则该函数执行反向查找地址。

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

如果您的主机文件未使用您传递的IP进行更新,则会发送反向DNS查询。我假设没有DNS服务器包含主机的名称和地址,因此您需要更新主机文件。在linux中,它位于/ etc / hosts中。在Windows中,它位于C:\ Windows \ System32 \ drivers \ etc

中 顺便说一句,你也可以使用:

InetAddress.getLocalHost()

但如果没有在hosts文件中正确输入,您将遇到同样的问题。

我希望这会有所帮助。