«Back to Home

Core Java

Topics

InetAddress Class In Java

InetAddress Class

In Java, The InetAddress class shows an IP address and the java.net.InetAddress class gives methods to get the IP of any host name.
 
For example

www.google.com.
 
Methods of InetAddress class

public static InetAddress getByName(String host) throws UnknownHostException

This method is used to return the object of InetAddress contains LocalHost IP and name.
 
public static InetAddress getLocalHost() throws UnknownHostException

This method is used to return the object of InetAdddress, which contains the local host name and address.
 
public String getHostName()

This method is used to return the host name of the IP address.
 
public String getHostAddress()

This method is used to return the IP address in the string format.
 
Let’s see an example of InetAddress class, given below.
 
Code
  1. import java.io.*;  
  2. import java.net.*;  
  3. public class InetAddressClass {  
  4.     public static void main(String[] args) {  
  5.         try {  
  6.             InetAddress ip = InetAddress.getByName("www.google.com");  
  7.   
  8.             System.out.println("Host Name: " + i.getHostName());  
  9.             System.out.println("IP Address: " + i.getHostAddress());  
  10.         } catch (Exception e) {  
  11.             System.out.println(e);  
  12.         }  
  13.     }  
  14. }  
11

Output

12

Summary

Thus, we learnt Java InetAddress class shows an IP address and the java.net.InetAddress class gives methods to get the IP of any host name and also learnt how we can use it in Java.