skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Saturday, October 6, 2012

Hostname from IP Address

Posted by Raju Gupta at 12:23 AM – 1 comments
 
The class instantiates an InetAddress object through the IP address provided as commandline argument and invokes the getHostName() through that object which returns the Hostname for the corresponding IP.

Incase of any invalid IP an UnknownHostException is thrown which is handeled in code by displaying an error message.

The point to be noted is that while providing IP address through command line leave a single blank space after the class name.
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Hostname
   {
  
   public static void main ( String[] args )
      {
    String IP = args[0];
      try
         {
         InetAddress[] addresses = InetAddress.getAllByName(IP);

         for ( int i=0; i<addresses.length; i++ )
            {
            String hostname = addresses[i].getHostName();
   //String hostname = addresses[i].getHostAddress();
            System.out.println( hostname );
            }
         }
      catch ( UnknownHostException e )
         {
         System.out.println( "Could not resolve IP Address to Hostname.....Unknown Host" );
         }

      }
   }

One Response so far.

  1. Unknown says:
    April 22, 2014 at 9:32 PM

    thanks

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger