java get ip address code example

Example 1: How to get server IP address in java

import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetServerIPAddress
{
   public static void main(String[] args)
   {
      InetAddress ia;
      try
      {
         ia = InetAddress.getLocalHost();
         System.out.println("get server ip address: " + ia);
      }
      catch(UnknownHostException ex)
      {
         ex.printStackTrace();
      }
   }
}

Example 2: 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:

Java Example