Java program to find IP address

Let’s learn java program to find IP address.

java program to find IP address

Java program to find IP address

To get ip address java first let’s understand what is an IP address. IP address is an identifier usually connected to TCP/IP network.

If you see an IP address in detail you will notice that it’s basically four numbers separated by dots like,

192.168.1.1

Also read – create file java program

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 InetAddress.getLocalHost() method and InetAddress.getHostName() method to get IP address and HostName of any server.

Now let’s see finding IP address of a URL in java,

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;

public class DisplayIPAddress
{
   public static void main(String[] args) throws Exception
   {
      InetAddress address = InetAddress.getLocalHost();
      System.out.println("Machine IP Address : " + (address.getHostAddress()).trim());
 
      // public IP address
      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("The public IP Address : " + ipAddress);
   }
}



Output:

Machine IP Address : 10.0.5.203
The public IP Address : 35.104.23.98