Java中獲取Linux的IP地址可以使用InetAddress類的相關方法。下面是獲取本地IP地址的示例代碼:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Main {
public static void main(String[] args) {
try {
InetAddress localhost = InetAddress.getLocalHost();
System.out.println("IP Address: " + localhost.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
這段代碼使用getLocalHost()
方法獲取本地主機的InetAddress對象,然后使用getHostAddress()
方法獲取IP地址。