user14345
user14345

Reputation: 73

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.

Upvotes: 7

Views: 14435

Answers (5)

geekR
geekR

Reputation: 1

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

Upvotes: 0

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

Try this out....

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

Upvotes: 0

Shashank Kadne
Shashank Kadne

Reputation: 8101

You can use getHostName() method of InetAddress class.

Upvotes: 0

ioreskovic
ioreskovic

Reputation: 5699

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

Upvotes: 4

user1920811
user1920811

Reputation:

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

Upvotes: 11

Related Questions