Getting the IP address of the current machine using Java

To get the IP address of the current machine using Java, you can use the InetAddress.getLocalHost method of the java.net package.

Here is an example of how you can do this:

import java.net.InetAddress;

InetAddress ip = InetAddress.getLocalHost();
System.out.println("Current IP address : " + ip.getHostAddress());

This will print the IP address of the current machine to the console.

Note that the getLocalHost method may throw an UnknownHostException if it is unable to resolve the local host. You should handle this exception in your code.

try {
  InetAddress ip = InetAddress.getLocalHost();
  System.out.println("Current IP address : " + ip.getHostAddress());
} catch (UnknownHostException e) {
  System.out.println("Unable to resolve local host");
}

Alternatively, you can use the NetworkInterface class to get the IP address of the current machine.

Here is an example of how you can do this:

import java.net.NetworkInterface;
import java.util.Enumeration;

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
  NetworkInterface ni = interfaces.nextElement();
  Enumeration<InetAddress> addresses = ni.getInetAddresses();
  while (addresses.hasMoreElements()) {
    InetAddress addr = addresses.nextElement();
    if (!addr.isLinkLocalAddress() && !addr.isLoopbackAddress() && addr.isSiteLocalAddress()) {
      System.out.println("Current IP address : " + addr.getHostAddress());
    }
  }
}

This will print the IP address of the current machine to the console.