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