How to get the IP address of a localhost in Java
This shot covers how to get the
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:
-
Get a list of all the network interfaces using the
getNetworkInterfaces()method of theNetworkInterfaceclass. -
For every network interface, loop over all the IP addresses.
-
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();}}}