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 allocated to computer and connected to TCP/IP network.

java program to find IP address of a system

If you see an IP address in detail you will notice that it’s basically four numbers separated by dots 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 program to find ip address of a system.

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