Java Networking – inetAddress

Java.Net Package

  • This Class represent as Internet Protocol (IP) address.
  • The java.net.InetAddress class provides methods to get an IP of Host name.

Example

InetAddress ip= InetAddress.getByName(“www.examradar.com”);System.out.println(“ip:”+ip);

Output:

Ip: examradar.com./166.62.27.173

Lets check below example

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

public class getipofhost {
public static void main(String[] args)
throws Exception {
InetAddress ip = InetAddress.getByName("www.examradar.com");
System.out.println("IP:  "+ip);

  }

}
OUTPUT
IP:  www.examradar.com/166.62.27.173

 

InetAddres : Method

Method Description
Public static inetAddress
getLocalHost()
through UnknownHostException
Returns the address of the local host

 

Lets check below example

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

public class getipofhost {
public static void main(String[] args)
throws Exception {
  InetAddress ip = InetAddress.getLocalHost();
  System.out.println("LocalHost:  "+ip);
  }

}
OUTPUT
LocalHost:  user-PC/192.168.225.32

 

InetAddres : Method

Method Description
Public string getHostName()
through UnknownHostException
It returns the hostname of the IP Address

 

Let’s check below example:

 

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

public class getipofhost {
public static void main(String[] args)

 throws Exception {
 InetAddress ip = InetAddress.getByName("192.168.225.32");
 System.out.println("HostName:  "+ip.getHostName());
 }

}
OUTPUT
HostName:  user-PC

 

InetAddres : Method

Method Description
Public string getHostAddress() It returns the IP Address in string formate

 

Lets check below example:

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

public class getipofhost {

public static void main(String[] args)
throws Exception {
  InetAddress ip = InetAddress.getByName("www.examradar.com");
  System.out.println("HostAddress:  "+ip.getHostAddress());

  }

}
OUTPUT:
HostAddress:  166.62.27.173

 

Other Methods of inetAddress

Method Description
string toString() Converts the IP address to String formate
boolean equal(Object obj) Compares this object against specified object
Static InetAddress[] getAllByName(String host) Returns an array of its IP addresses ,based on configured name service on the system
Static InetAddress[] getLoopbackAddress() Returns loopback address