2016-10-26 70 views
2

我想製作一個小型的android應用程序,它可以從連接的LAN網絡獲取IP地址和主機名。我有一個運行良好的代碼,可以在已連接的局域網中獲得IP地址,但我不知道如何獲取其IP地址的主機名。在哪裏需要更改代碼。對不起,英文不好。如何獲得Android的IP地址的主機名?

這是我在LAN網絡獲取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(); 
    } 
+0

什麼項目你在你的hosts文件 –

+0

看看這個它會解決你的問題:http://stackoverflow.com/questions/21521844/how-to-resolve-network-host-names-from-ip-address –

+0

Shreyas,我添加此InetAddress.getByName(「192.168。 1.2「)。getHostName() 打開你的鏈接後,但仍然給我相同的IP 192.168.1.2 –

回答

2

使用.getHostname()代碼

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

這將工作,只有當它有條目在主機文件 –

+0

當我通過「192.168.1.4」它給我相同的IP地址,我通過「192.168.1.4」。 –