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:wwual.wtturi.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.