Getting Your Own Device IP Address using Java

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 classimport java.io.*;// Importing InetAddress class from java.net packageimport java.net.InetAddress;Â
// Main classpublic 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");        }    }} |
My IP Address is: 127.0.0.1
Â




