繁体   English   中英

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

[英]How to get host name based on IP address?

我想在程序中基于给定的IP地址找到主机名。 是否可以获取,如果可以,请提供代码。 谢谢。

是的,有可能。

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

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

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

资源

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

试试这个...

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

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM