可以使用InetAddress類中的getLocalHost()方法來獲取當前IP地址。代碼示例如下:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetIPAddress {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
System.out.println("當前IP地址:" + address.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
運行結果:
當前IP地址:192.168.0.100