基于IP地址如何获取主机名?

7

我想在我的程序中根据给定的IP地址找到主机名。

如果可以,请提供代码。谢谢。

5个回答

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
  }
}

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


0

嘿,我正在使用上述方法,但是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);
        } 

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

0

试一试....

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


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