【问题标题】:How to get Host name of ip address in android?如何在android中获取IP地址的主机名?
【发布时间】:2017-03-09 02:15:51
【问题描述】:

我想制作一个小型 android 应用程序,从连接的 LAN 网络获取 IP 地址和主机名。我有一个代码可以很好地在已连接的 LAN 网络中获取 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 文件中有哪些条目
  • 看看这个它会解决你的问题:stackoverflow.com/questions/21521844/…
  • Shreyas,我在打开您的链接后添加了这个 InetAddress.getByName("192.168.1.2").getHostName() 但仍然给我相同的 ip 192.168.1.2
  • 不,他们给我的 ip 与我在 getByName 方法中传递的相同。
  • 主机名将由 DNS 服务器提供。您连接到哪个 DNS 服务器?

标签: java android networking ip hostname


【解决方案1】:

使用 .getHostname()

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

【讨论】:

  • 当我传递“192.168.1.4”时,它给了我与传递“192.168.1.4”相同的IP地址。
猜你喜欢
  • 1970-01-01
  • 2014-04-12
  • 2012-05-31
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
  • 2018-01-02
  • 2018-08-26
相关资源
最近更新 更多