Java program to find IP address

Let’s learn java program to find IP address.

Java program to find IP address

An IP address is an identifier allocated to computer and connected to TCP/IP network.

java program to find IP address

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 or system ip address and to find public ip address.

// how to get system ip address in java
// how to get public ip address using java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
public class FindIPAddress
{
   public static void main(String[] args) throws UnknownHostException
   {
      InetAddress address = InetAddress.getLocalHost();
      System.out.println("System IP Address : " + (address.getHostAddress()).trim());
      // to get public IP address in java
      String ipAddress = "";
      try
      {
         URL url = new URL("http://example.com");
         BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
         // reads system IPAddress
         ipAddress = br.readLine().trim();
      }
      catch (Exception ex)
      {
         ipAddress = "Error occurred!!";
      }
      System.out.println("public IP Address : " + ipAddress);
   }
}


Output:

System IP Address : 10.0.5.203
public IP Address : 35.104.23.98


java get all ip addresses

To get all ip addresses first pass any host name to InetAddress.getAllByName() method.

Then call getHostAddress() method to get list of all IPs.

import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetAllAddresses
{
   public static void main(String[] args)
   {
      try
      {
         InetAddress[] inet = InetAddress.getAllByName("www.google.com");
         for(InetAddress ia : inet)
         {
            System.out.println(ia.getHostAddress());
         }
      }
      catch(UnknownHostException ex)
      {
         ex.printStackTrace();
      }
   }
}


Also read – major features of java