Java program to get the IP address

In today’s post we are going to learn how to get the ip address.This is very simple and easy program among all basic programs of java.In this program we are importing the classes “import java.net.InetAddress”,”import java.net.UnknownHostException”.Here we are declaring a variable for InetAddress class. This variable is used to store the ip address. If any Error is occurred then we need to handle those errors.For this we are including the try block and catch block to handle these errors.
Let us write the code for this:

import java.net.InetAddress;
import java.net.UnknownHostException;
public class ip_address
{
  public static void main(String[] args) {
  InetAddress ip;
  try 
   {
     ip = InetAddress.getLocalHost();
     System.out.println("Current IP address : " + ip.getHostAddress());
    } 
  catch(UnknownHostException e)
   {
      System.out.println(e);
    }
 }
}

Output:
ip_address
You can download the source code:download

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Java and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s