[an error occurred while processing this directive] [an error occurred while processing this directive]

To retrieve the IP address from Host Name, vice-versa

[an error occurred while processing this directive]

                         

Here we are going to explain the method to find out the IP address from host name and to vice verse. Here we are give a complete example named HostLookup.java. In which we call a InetAddress and make a object and pass the input value in it. After that we put the condition, if the user enter any host name then we call the input value with getHostAddress() which return the IP address of that Host . If the user enter any IP address then we call the input value with getHostName() which return the host name of that Host.

Apart from all of this we put the condition for wrong entry system prints "localhost" and if user want to exit from the program then he/she should need to write "exit". The complete code of the example is as under.

Here is the Code of the Example :

HostLookup.java

import java.net.*;
import java.io.*;

public class HostLookup {
  public static void main (String[] args) {
    if (args.length > 0) { 
      for (int i = 0; i < args.length; i++) {
        System.out.println(lookup(args[i]));
      }
    }
    else {  
      BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter the name and IP addresses. ");
      System.out.println("Enter \"exit\".");
      try {
        while (true) {
          String host = buffer.readLine();
          if (host.equalsIgnoreCase("exit")) {
            break;
          }
          System.out.println(lookup(host));
        }
      }
      catch (IOException ex) {
        System.err.println(ex);
      }
    }
  }
  private static String lookup(String hostname) {
    InetAddress node;
    try {
      node = InetAddress.getByName(hostname);
    }
    catch (UnknownHostException ex) {
      return "Cannot find host " + hostname;
    }
    if (isHostname(hostname)) {
      return node.getHostAddress();
    }
    else {  
      return node.getHostName();
    }
  }
  private static boolean isHostname(String host) {
    // Is this an IPv6 address?
    if (host.indexOf(':'!= -1return false;
    char[] ca = host.toCharArray();
  for (int i = 0; i < ca.length; i++) {
    if (!Character.isDigit(ca[i])) {
      if (ca[i!= '.'return true;
    }
  }
    return false;

   }  

Here is the Output of the Example :

C:\ashish\complete>javac HostLookup.java

C:\ashish\complete>java HostLookup
Enter the name and IP addresses.
Enter "exit".
roseindia
Cannot find host roseindia
roseindi
192.168.10.104
192.168.10.103
comp20

localhost

Download of this example.

 

                         

[an error occurred while processing this directive]