简体   繁体   中英

How to get host name based on IP address?

I want to find the Host Name based on the given IP address in my program. Is it possible to get it, if yes can you please provide the code. Thanks.

Yes, its possible.

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

Something like this should point you in the right direction:

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

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

试试这个...

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

Hey I m using above methods bt the getHostName() method is not returning the host name of given ip.

see code:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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