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

IP address of localhost from java program is one of the most asked java interview question.

An IP address is an identifier allocated to computer and 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 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.

Also read – create file java program

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 dsiplay/print the IP address of system or localhost,

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

public class FindIPAddress
{
   public static void main(String[] args) throws Exception
   {
      InetAddress address = InetAddress.getLocalHost();
      System.out.println("Machine 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:

Machine IP Address : 10.0.5.203
public IP Address : 35.104.23.98