Java program to find IP address of a system

Let’s learn java program to find IP address of a system .

Java program to find IP address of a system

An IP address is an identifier used to identify hardware devices like computer, mobile, router etc., on a network.

IP address allow devices to connect to one another and transfer data on a local network or over the internet.

java program to find IP address of a system

Each IP address is a string of numbers separated by dots or periods like this,

192.168.1.1

Computers don’t use geographical addresses but rather use string of numbers called an IP address. These IP addresses are how the device is involved in passing the message to know who is sending, what to whom.

IP (Internet Protocol) address represent where you live on the internet. IP address are needed to send messages to computers outside of your network.

In java we have two methods,

  • InetAddress.getLocalHost() method – returns the address of the local host.
  • InetAddress.getHostAddress() method – returns the raw IP address in a string format.

Now let’s see java program to find ip address.

import java.net.InetAddress;
public class IPAddressExample
{
   public static void main(String[] args) throws Exception 
   {
      /* InetAddress getLocalHost() : Returns the address 
       * of the local host. This is achieved by retrieving 
       * the name of the host from the system, then resolving 
       * that name into an InetAddress. Note: The resolved 
       * address may be cached for a short period of time.
      */
      InetAddress inet = InetAddress.getLocalHost();
      // getHostAddress(): Returns the IP address string in textual presentation
      System.out.println("IP Address is: ");
      System.out.println(inet.getHostAddress());
   }
}

Output:

IP Address is:
192.163.2.1


Also read – major features of java

Reference – oracle docs