This shot covers how to get the
InetAddress
classWe 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;
import java.net.*;public class Main {public static void main(String[] args) throws UnknownHostException {InetAddress localHost = InetAddress.getLocalHost();System.out.println(localHost.getHostAddress());}}
NetworkInterface
classA 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 the NetworkInterface
class.
For every network interface, loop over all the IP addresses.
For every IP address, check if it is the local address or not.
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();}}}