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

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


LOCAL HOST : anandkumar-inl

IP :

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

No comments:
Write comments