Learn how to get IP address of a device in Java

In this tutorial, we will learn how to make a program to get the IP address of the device in Java. The first question before making this program that should click on everyone’s mind is “what is IP address??.”
An IP address is an address that gives a unique identity to the device in a computer network. Which is written in human readable notation, such as 192.168.1.45 (in IPv4)   that uses Internet Protocol, a protocol is simply a set of rules.

Program to get the IP address of a device in Java

In  Java to find the IP address, we need to understand the  java.net package i.e collection of classes and interface and java.io package. The java.net package provides the infrastructure to networking in java.
Some important classes inside the java.net package are Authenticator,  InetSocketAddress, InetAddress, Inet4Address, NetworkInterface, Socket, URL and even more.
The  java.io package provides a set of input and output series used to read and write data the files.

Some important classes in the java.io package are BufferReader, BufferWriter, InputStreamReader, File and many more.

Steps followed in the program:

  1. The first step is to import the java.net.InetAddress class from the “java.net” package. which consists of a device IP address.
    //importing java.net package
    import java.net.*;
  2. Next, is to import the “java.io” package.
    //importing java.io package.
    import.java.io.*
  3. When we accessing the data from the file which does not exist so in this case an exception will be raised. For which we will use the concept of exceptions handling in java,  using throw keyword to suppress the error.
    For more information on exception handling please go through the given topics  – Java Exceptions, Errors , Exception Handling in Java.

    public class Main {
       public static void main(String[] args) throws Exception {
  4. Now, creating the object of the InetAddress class. The java.net.InetAddress class provides methods to get the IP of any hostname example codespeedy.com, www.google.com, etc.
    The getLocalHost() is a method in InetAddress class that returns the instance of InetAdddress containing local host_name and address. where localhost is the reference variable that gets the IP address of the system.

       //creating object of InetAddress class.
      InetAddress localhost = InetAddress.getLocalHost(); 
           System.out.println("System IP Address : " + 
                         (localhost.getHostAddress()).trim()); 
     
           // Finding public IP address .
          //where public_ipaddress is a refrence variable which is string.
           String public_ipaddress = "";
  5. The java string trim() method removes unnecessary spaces. Creating an object of URL class which is a representation of the Uniform Resource Identifier. For exception using Try and catch.
    Creating an object of InputStreamReader class that reads bytes and decodes to the character set and “.openStream” is the method from which you can read the content of the URL.

     try
            { 
                URL url_name = new URL("http://bot.whatismyipaddress.com"); 
          InputStreamReader sr =new InputStreamReader(url_name.openStream());
                BufferedReader sc =   new BufferedReader(sr); 
      
                // reads system IPAddress 
                systemipaddress = sc.readLine().trim(); 
            } 
            catch (Exception e) 
            { 
                systemipaddress = "Cannot Execute Properly"; 
            } 
            System.out.println("Public IP Address: " + systemipaddress +"\n"); 
        } 
    }

Also, the BufferedReader class is used which is similar to scanner class here it stores the public IP address with the help of the “.readLine () “method and finally printing it.

COMPLETE CODE:

 

// java.net.InetAddress class provides method to get ip address
import java.net.*; 
import java.io.*; 
 public class ipaddress
{ 
    public static void main(String args[]) throws Exception 
    { 
        // Returns the instance of InetAddress containing 
        // local host name and address 
        InetAddress localhost = InetAddress.getLocalHost(); 
        System.out.println("System IP Address : " + 
                      (localhost.getHostAddress()).trim()); 
  
        // Find public IP address 
        String systemipaddress = ""; 
        try
        { 
            URL url_name = new URL("http://bot.whatismyipaddress.com"); 
      InputStreamReader sr =new InputStreamReader(url_name.openStream());
            BufferedReader sc =   new BufferedReader(sr); 
  
            // reads system IPAddress 
            systemipaddress = sc.readLine().trim(); 
        } 
        catch (Exception e) 
        { 
            systemipaddress = "Cannot Execute Properly"; 
        } 
        System.out.println("Public IP Address: " + systemipaddress +"\n"); 
    } 
}

OUTPUT:

System IP Address : 100.64.152.163
Public IP Address: 106.212.140.205

Also, read:

Leave a Reply

Your email address will not be published. Required fields are marked *