java get current machine's IP address

java get current machine's IP address

To get the current machine's IP address in Java, you can use the InetAddress class from the java.net package. This class represents an IP address, and provides methods for working with IP addresses.

Here's an example of how to use the InetAddress class to get the current machine's IP address:

import java.net.InetAddress;

public class Main {
  public static void main(String[] args) throws Exception {
    InetAddress localHost = InetAddress.getLocalHost();
    String ipAddress = localHost.getHostAddress();
    System.out.println(ipAddress); // prints the current machine's IP address
  }
}
Source:ww‮ual.w‬tturi.com

In this example, the getLocalHost() method of the InetAddress class is used to get the InetAddress object for the current machine. The getHostAddress() method is then called on the InetAddress object to get the IP address as a string. The IP address is then printed to the console.

Please note that the getLocalHost() method may throw a UnknownHostException if the current machine's IP address cannot be determined.

Created Time:2017-11-03 22:21:09  Author:lautturi