在Java中獲取Linux系統的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: " + address.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class GetIPAddress {
public static void main(String[] args) {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (!address.isLoopbackAddress() && address.getHostAddress().indexOf(":") == -1) {
System.out.println("IP Address: " + address.getHostAddress());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
這兩種方法都可以獲取Linux系統的IP地址,其中第一種方法是獲取本地主機的IP地址,而第二種方法則是獲取所有網絡接口的IP地址。根據你的需求選擇合適的方法獲取IP地址即可。