如何根据IP地址获取主机名?

时间:2012-08-04 06:40:39

标签: java network-programming

我想根据程序中的给定IP地址找到主机名。 是否有可能得到它,如果是的话,请提供代码。谢谢。

6 个答案:

答案 0 :(得分:11)

是的,它可能。

import java.net.*;
public class HostName
{
  public static void main(String args[])
  {
    InetAddress inetAddress =InetAddress.getByName("127.64.84.2");//get the host Inet using ip
    System.out.println ("Host Name: "+ inetAddress.getHostName());//display the host
  }
}

答案 1 :(得分:4)

这样的事情应该指向正确的方向:

import java.net.InetAddress;
import java.net.UnknownHostException;

public class DNSLookup {
  public static void main(String args[]) {
    try {
      InetAddress host;
      if (args.length == 0) {
        host = InetAddress.getLocalHost();
      } else {
        host = InetAddress.getByName(args[0]);
      }
      System.out.println("Host:'" + host.getHostName()
          + "' has address: " + host.getHostAddress());

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

Source

答案 2 :(得分:0)

您可以使用getHostName()类的InetAddress方法。

答案 3 :(得分:0)

尝试一下......

System.out.println(InetAddress.getByName("IP_ADDR").getHostName());

答案 4 :(得分:0)

嘿我使用上面的方法bt getHostName()方法没有返回给定ip的主机名。

见代码:

try {
//        This is ip of tutorialspoint.com    
           InetAddress addr2 = InetAddress.getByName("127.64.84.2");     
            op.setText("Host name is: "+addr2.getHostName());
        }   
        catch ( UnknownHostException e3) {  
            op.setText("Error: Host not found" + e3);
        } 

答案 5 :(得分:0)

import java.net.*;

public class GetHostNameFromIPAddress {

        public static void main(String[] args) {
            try {
                 InetAddress inetAddr = InetAddress.getByName("163.53.76.55");
                 // Get the host name
                 String hostname = inetAddr.getHostName();
                 // Get canonical host name
                 String canonicalHostname = inetAddr.getCanonicalHostName();
                 System.out.println("Hostname: " + hostname);
                 System.out.println("Canonical Hostname: " +        canonicalHostname);
            }
            catch (UnknownHostException e) {
                 System.out.println("Host not found: " + e.getMessage());
            }
        }

}