在Java中获取Linux本机IP地址
在Java中获取Linux本机IP地址有几种方法,以下是几种常用的实现方式:

方法1:使用InetAddress类
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class GetLocalIP {
public static void main(String[] args) {
try {
// 获取所有网络接口
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
// 获取该接口的所有IP地址
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
// 排除回环地址和IPv6地址(如果只需要IPv4)
if (!inetAddress.isLoopbackAddress() && !inetAddress.getHostAddress().contains(":")) {
System.out.println("IP地址: " + inetAddress.getHostAddress());
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}
方法2:使用命令行工具(更可靠)
在Linux环境中,可以通过执行命令来获取IP地址:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class GetLocalIP {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("hostname -I");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String ip = reader.readLine();
System.out.println("IP地址: " + ip.trim());
} catch (Exception e) {
e.printStackTrace();
}
}
}
方法3:使用第三方库(推荐)
使用Apache Commons Net库可以更方便地获取网络信息:
import org.apache.commons.net.util.SubnetUtils;
public class GetLocalIP {
public static void main(String[] args) {
// 获取默认网络接口的IP
SubnetUtils utils = new SubnetUtils("0.0.0.0/0");
String ip = utils.getInfo().getAddress();
System.out.println("IP地址: " + ip);
}
}
注意事项
- 回环地址:127.0.0.1是回环地址,通常不需要
- IPv6地址:如果只需要IPv4地址,需要过滤掉包含":"的地址
- 多网卡:服务器可能有多个网卡,需要确定要获取哪个网卡的IP
- 容器环境:在Docker等容器环境中,可能需要特殊处理
获取特定网卡的IP
如果需要获取特定网卡的IP(如eth0):
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
public class GetSpecificInterfaceIP {
public static void main(String[] args) {
try {
NetworkInterface networkInterface = NetworkInterface.getByName("eth0");
if (networkInterface != null) {
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress() && !inetAddress.getHostAddress().contains(":")) {
System.out.println("eth0的IP地址: " + inetAddress.getHostAddress());
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}
方法中,方法2(执行hostname -I命令)在Linux环境中通常是最可靠的,因为它直接使用了系统命令获取IP地址。


