Java Examples - Get Local IP Address and Hostname
In Java, you can use the standard network library to obtain the local IP address and hostname.
The following example demonstrates how to use the getLocalHost and getLocalAddress() methods of the InetAddress class to obtain the local hostname and IP address:
Main.java file
import java.net.InetAddress;
import java.net.UnknownHostException;
public class NetworkInfo {
public static void main(String[] args) {
try {
//Get the local host object
InetAddress localHost = InetAddress.getLocalHost();
//Get the hostname
String hostName = localHost.getHostName();
System.out.println("Hostname:" + hostName);
//Get the IP address
String hostAddress = localHost.getHostAddress();
System.out.println("IP address:" + hostAddress);
} catch (UnknownHostException e) {
System.err.println("Unable to obtain local IP address and hostname:" + e.getMessage());
e.printStackTrace();
}
}
}
Description
InetAddress.getLocalHost(): Gets theInetAddressobject representing the local host.getHostName(): Gets the hostname of the local host.getHostAddress(): Gets the IP address of the local host.
Exception Handling
UnknownHostException: Thrown when the local hostname or IP address cannot be determined.
The output of the above code is:
主机名: your-hostname IP地址: 192.168.1.2Other Extensions
Java Examples