Ensode.net
Google
 

Home
Blog
Guides
Tips
Articles
Utilities
Reviews
About Us
Contact us


Facebook profile

XML

Implementing NSLookup In Java
Bookmark and Share

Introduction

NSLookup is a command line utility that, given an IP address, returns the corresponding host name and vice versa. NSLookup can be found in most Unix/Linux systems and in some Microsoft Windows systems. This article explains how to write an NSLookup clone in Java.

InetAddress

The java.net.InetAddress class included in the Java Development Kit (JDK) contains all the methods we need to clone nslookup. Especially handy is it's getByName() method. getByName() takes a String object as it's sole parameter, either the host name or a String representation of the host's IP address must be passed in this parameter. InetAddress.getByName() returns an instance of InetAddress for this host. Once we have an instance of InetAddress obtained this way, we can call it's getHostByName() and getHostAddress() methods, which return the host name and IP address for the host, respectively.

The following Java class demonstrates this procedure:


package net.ensode.nslookupdemo;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class NsLookup
{

  public void resolve(String host)
  {
    try
    {
      InetAddress inetAddress = InetAddress.getByName(host);

      System.out.println("Host: " +
          inetAddress.getHostName());
      System.out.println("IP Address: " +
          inetAddress.getHostAddress());
    }
    catch (UnknownHostException e)
    {
      e.printStackTrace();
    }
  }

  public static void main(String[] args)
  {
    new NsLookup().resolve(args[0]);
  }

}


        

To execute the above example, either the host name or IP address must be passed as a parameter to the resulting executable:
java net.ensode.nslookupdemo.NsLookup ensode.net
And the output would look like this:


Host: ensode.net
IP Address: 216.154.217.165

        

Summary

As we have seen in this article, the java.net.InetAddress class makes it very easy to write an NSLookup clone in Java. No extra libraries are necessary, everything we need is included in this class.

Resources


Java EE 6 Development With NetBeans 7
Java EE 6 Development With NetBeans 7


Java EE 6 with GlassFish 3 Application Server
Java EE 6 with GlassFish 3 Application Server


JasperReports 3.5 For Java Developers
JasperReports 3.5 For Java Developers