find ip adress in java code example

Example: Java program to find IP address

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);
   }
}

Tags:

Misc Example