Get IP Address Java

Hey guys!! Welcome to flower brackets blog. Today we are going to learn get ip address in java.

get ip address java

What is an IP address?

IP (Internet Protocol) address represent where you live on the internet. IP address are needed to send messages to computers outside of your network.

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 address is an identifier usually connected to TCP/IP network. If you look at an IP address in detail you will notice that it’s basically four numbers separated by dots like,

192.168.1.1

In java we have InetAddress.getLocalHost() method and InetAddress.getHostName() method to get IP address and HostName of any server.

Now let’s see how to get server IP address and hostname in java,

Example:

import java.net.InetAddress;
import java.net.UnknownHostException;

public class DisplayIPAddress
{
   public static void main(String[] args)
   {
      try
      {
         InetAddress address = InetAddress.getLocalHost();
         String hostname = address.getHostName();
         System.out.println("Your IP address : " + address);
         System.out.println("Your Hostname : " + hostname);
      } 
      catch(UnknownHostException ex) 
      {
         ex.printStackTrace();
      }
   }
}

Output:

Your IP address : FlowerBrackets-mac/192.168.0.5
Your Hostname : FBapple-mac


Java program to find IP address of your computer

Now let’s see java program to find IP address of your (system) computer and public IP address using online utility,

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());
 
      // here we are finding public IP address
      String ipAddress = "";     
      try
      {
          URL url = new URL("http://bot.whatismyipaddress.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


Conclusion

That’s it guys. This was all about how to get server IP address and hostname in java. I hope you have understood the concept.

You can subscribe to my blog flower brackets if you haven’t already.

Do share this article if you like.

Related Posts