簡體   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