InetAddress and it’s use

The class InetAddress under java.net package is helpful to retrieve some important host specific details such as IP address, host name and etc

Here is code snippet which does this. This might be useful for somebody.

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

public class HostNameAndAdress {
	public static void main (String args[]){
		try {
		    InetAddress addr = InetAddress.getLocalHost();

		    // Get IP Address
		    byte[] ipAddr = addr.getAddress();

		    // Get hostname
		    String hostName = addr.getHostName();
		    String fullyQualifiedHostName = addr.getCanonicalHostName() ;
		    String hostAddress = addr.getHostAddress() ;

		    System.out.println("Host Name : "+hostName) ;
		    System.out.println("Host IP Address : "+hostAddress) ;
		    System.out.println("Host Name with domain name suffix : " + fullyQualifiedHostName) ;

		} catch (UnknownHostException e) {
			e.printStackTrace() ;
		}
	}

}

 

Bookmark and Share

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>