java - 如何在android中获取IP地址的主机名?

标签 java android networking ip hostname

我想制作一个小型 Android 应用程序,从连接的 LAN 网络获取 IP 地址和主机名。我有一个运行良好的代码,可以在连接的 LAN 网络中获取 ip 地址,但我不知道如何获取其 ip 地址的主机名。我需要更改代码的地方。抱歉英语不好。

Here is my code for getting ip address in lan network

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

最佳答案

使用.getHostname()

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

关于java - 如何在android中获取IP地址的主机名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40266930/

相关文章:

python - 获取运行python脚本的Windows计算机的名称?

Python:如何 ping 一个 IP 地址范围?

rhel - 显式声明 lib 时出现 UnsatisfiedLinkError 异常

java - 如何通过自动滚动将 JTextPane 的 Caret 位置居中?

android - Retrofit2 SocketTimeOutException

c# - Network Down 上的 TcpClient 连接状态问题

java - 无法在尚未调用 Looper.prepare() android 服务的线程内创建处理程序

java - Hazelcast spring 模式配置错误

android - 异步更新 Android 上下文菜单

android - 在带有填充角的自定义按钮上添加点击效果