Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
network
ip address
localhost
communitycreator

How to get the IP address of a localhost in Java

abhilash

This shot covers how to get the IP addressA unique address that identifies a device on the internet or a local network. of a local machine/localhost using Java.

Using the InetAddress class

We can use the getLocalHost() static method of the InetAddress class to obtain the localhost IP address.

You must import the java.net package before you can use the InetAddress class, as shown below:


import java.net.InetAddress;

Code

Example 1

import java.net.*;

public class Main {

    public static void main(String[] args) throws UnknownHostException {
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println(localHost.getHostAddress());

    }
}

Using the NetworkInterface class

A computer can have many network interfaces, and each interface can be assigned to multiple IP addresses. The IP address may or may not be reachable outside the machine.

Another approach is as follows:

  1. Get a list of all the network interfaces using the getNetworkInterfaces() method of the NetworkInterface class.

  2. For every network interface, loop over all the IP addresses.

  3. For every IP address, check if it is the local address or not.

Example 2

import java.net.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        try {
            Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
            while( networkInterfaceEnumeration.hasMoreElements()){
                for ( InterfaceAddress interfaceAddress : networkInterfaceEnumeration.nextElement().getInterfaceAddresses())
                    if ( interfaceAddress.getAddress().isSiteLocalAddress())
                        System.out.println(interfaceAddress.getAddress().getHostAddress());
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }

    }
}

RELATED TAGS

java
network
ip address
localhost
communitycreator
RELATED COURSES

View all Courses

Keep Exploring