The example here show you how to get an IP or host address using the java.net.InetAddress
class. To get an instance of InetAddress
we call a static method of this class, the method is getLocalHost()
, which return the local host address. Next, to get the IP address we can call the getHostAddress()
method.
package org.kodejava.net;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class LocalHostIpAddress {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress();
System.out.println("IP Address = " + ip);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
The result of this code snippet:
IP Address = 30.30.30.60
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024