Advanced Java Programming - Old Questions

11. What is InetAddress class? Discuss.

5 marks | Asked in 2073

The InetAddress class represents an IP address, both IPv4 and IPv6. The java.net.InetAddress class provides methods to get the IP of any host name for example www.google.com, www.facebook.com, etc. We can use the InetAddress class if we need to convert between host names and Internet addresses.

Commonly used methods of InetAddress class:

  • getByName(String host): creates an InetAddress object based on the provided hostname.
  •  getByAddress(byte[] addr): returns an InetAddress object from a byte array of the raw IP address.
  •  getAllByName(String host): returns an array of InetAddress objects from the specified hostname, as a hostname can be associated with several IP addresses.
  • getLocalHost(): returns the address of the localhost.

To get the IP address/hostname you can use a couple of methods below:

  •  getHostAddress(): it returns the IP address in string format.
  • getHostname(): it returns the host name of the IP address.

Example:

import java.io.*;  

import java.net.*;  

public class InetDemo{  

public static void main(String[] args){  

try{  

InetAddress ip=InetAddress.getByName("www.collegenote.net");

System.out.println("Host Name: "+ip.getHostName());  

System.out.println("IP Address: "+ip.getHostAddress());  

}catch(Exception e){

    System.out.println(e);}  

}  

}