如何在Android中获取IP地址的主机名?

4

我希望能制作一个小型的安卓应用程序,从连接的局域网中获取IP地址和主机名。我已经编写了一个代码,在连接的局域网中可以很好地获取IP地址,但我不知道如何获取它们的主机名。请问该在代码中做出什么改变。抱歉我的英语不好。

以下是我的代码,用于获取局域网中的IP地址

String connections = "";
    InetAddress host;
    try
    {
        host = InetAddress.getByName("192.168.1.1");
       byte[] ip = host.getAddress();
       for(int i = 1; i <= 254; i++)
        {
            ip[3] = (byte) i;
            InetAddress address = InetAddress.getByAddress(ip);

            if(address.isReachable(100))
            {


                System.out.println(address + " machine is turned on and can be pinged "+address.getCanonicalHostName());
                connections+= address+"\n";
            }
            else if(!address.getHostAddress().equals(address.getHostName()))
            {
                System.out.println(address + " machine is known in a DNS lookup");
                System.out.println(address.getHostAddress()+"host Name:"+ address.getHostName());
            }

        }
        tv.setText(connections);

    }
    catch(UnknownHostException e1)
    {
        e1.printStackTrace();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

你的 hosts 文件中有哪些条目? - Shreyas Sarvothama
看这个链接,它会解决你的问题:http://stackoverflow.com/questions/21521844/how-to-resolve-network-host-names-from-ip-address - Shreyas Sarvothama
Shreyas,我在打开你的链接后添加了InetAddress.getByName("192.168.1.2").getHostName(),但仍然得到相同的IP地址192.168.1.2。 - Umar Iqbal
代码是正确的,你需要在Windows/Unix中找到一个叫做hosts文件的东西,并为那些IP地址分配一个名称。你知道在哪里找hosts文件吗? - Shreyas Sarvothama
抱歉,这里是链接:http://www.howtogeek.com/140576/how-to-edit-the-hosts-file-on-android-and-block-web-sites/ - Shreyas Sarvothama
显示剩余9条评论
1个回答

5

使用 .getHostname()

InetAddress addr = InetAddress.getByName("192.168.1.1");
String host = addr.getHostName();
System.out.println(host);

7
当我传递“192.168.1.4”时,它会给我相同的 IP 地址,即我所传递的“192.168.1.4”。 - Umar Iqbal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接