Open In App

Getting Your Own Device IP Address using Java

Last Updated : 08 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

An Internet Protocol address (IP address) is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. An IP address serves two principal functions: host or network interface identification and location addressing. There are two versions of internet protocol addresses which are named as follows:

  • IPv4
  • IPv6

An IPv4 Addresses consists of 32 bits which limit the address space to 4294967296 (232) possible unique addresses. IPv4 reserves some addresses for special purposes such as private networks (~18 million addresses) or multicast addresses (~270 million addresses). The rapid exhaustion of IPv4 address space prompted the Internet Engineering Task Force to explore new technologies to expand the addressing capability on the Internet. This new generation of Internet Protocol was eventually named Internet Protocol Version 6 (IPv6) in 1995. The address size was increased from 32 to 128 bits (16 octets), thus providing up to 2128 (approximately 3.403×1038) addresses. 

Implementation:  

Pseudo-code is as follows:

InetAddress myIP = InetAddress.getLocalHost();
System.out.println(myIP.getHostAddress());

Example

Java




// Java Program to Find IP address of Own Device
 
// Importing input output class
import java.io.*;
// Importing InetAddress class from java.net package
import java.net.InetAddress;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Try block to check for exceptions
        try {
 
            // Creating an object of InetAddress class to
            // get the Ip address
            InetAddress myIP = InetAddress.getLocalHost();
 
            // Display message only
            System.out.println("My IP Address is : ");
 
            // Print and display the IP address
            System.out.println(myIP.getHostAddress());
        }
 
        // Catch block to handle the exceptions
        catch (Exception e) {
 
            // Display message to be printed on console
            // as the exception occurs
            System.out.println("Some Error Occurred");
        }
    }
}


Output

My IP Address is:
127.0.0.1

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads