Showing posts with label Domain Name lookup. Show all posts
Showing posts with label Domain Name lookup. Show all posts

IP and Domain Name Lookup using Java

 

In this tutorial we will see how to find IP address from domain name and how to find host from IP. We have used dnsjava open source library for this demo. You can download dnsjava jar from external link and can add it in your project.


import java.net.InetAddress;
import java.net.UnknownHostException;
import org.xbill.DNS.ExtendedResolver;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Name;
import org.xbill.DNS.PTRRecord;
import org.xbill.DNS.Record;
import org.xbill.DNS.Resolver;
import org.xbill.DNS.ReverseMap;
import org.xbill.DNS.Type;

public class FindDomain {

 public static void main(String[] args) {
   try {
    InetAddress address = InetAddress.getLocalHost();
    System.out.println("LOCAL ADDRESS : " + address.getHostAddress());
    System.out.println("LOCAL HOST : " + address.getHostName());

    InetAddress ipAddress = java.net.InetAddress.getByName("www.javadiscover.com");
    String ip = ipAddress.getHostAddress();
    System.out.println("\nJAVADISCOVER IP : " + ip);

    final InetAddress ip2 = InetAddress.getByName("74.125.135.121");
    final byte[] bytes = ip2.getAddress();
    final String host = getHostByIPAddress(bytes);
    System.out.println("\nJAVADISCOVER HOST : " + host);

   } catch (UnknownHostException e) {
    System.out.println("Host NOT Avaialble");
   }

  }

  public static String getHostByIPAddress(byte[] addr) throws UnknownHostException {

   Name name = ReverseMap.fromAddress(InetAddress.getByAddress(addr));

   // OPEN DNS SERVERS
   final String[] openDNS = new String[] {"208.67.222.222", "208.67.220.220"};
   final Resolver resolver = new ExtendedResolver(openDNS);
   final Lookup lookUp = new Lookup(name, Type.PTR);
   lookUp.setResolver(resolver);
   Record[] records = lookUp.run();
   if (records == null) {
    throw new UnknownHostException();
   }
   return ((PTRRecord) records[0]).getTarget().toString();
  }
}


OUTPUT:


LOCAL ADDRESS : 10.70.50.16
LOCAL HOST : anandkumar-inl

IP : 74.125.135.121

HOST : ni-in-f121.1e100.net.