Java获取linux指定网卡的ip
时间: 2024-09-13 10:04:36 浏览: 61
在Java中获取指定网卡的IP地址,可以通过Java的`NetworkInterface`类来实现。这个类提供了方法来查询网络接口的属性,包括IP地址。下面是一个基本的示例代码,用于获取特定网卡的IP地址:
```java
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class NetworkInterfaceExample {
public static void main(String[] args) {
try {
// 获取本机所有网络接口
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface netInterface = netInterfaces.nextElement();
// 根据实际情况修改网卡名称进行过滤,例如:"eth0", "ens33" 等
if (netInterface.getName().equalsIgnoreCase("指定网卡名称")) {
System.out.println("网卡名称: " + netInterface.getDisplayName());
// 获取所有该网卡的IP地址
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
System.out.println("IP地址: " + address.getHostAddress());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请注意,网卡名称(如"eth0", "ens33"等)需要根据实际情况进行替换。如果你不确定网卡的具体名称,可以先打印出所有网卡信息进行筛选。
阅读全文
相关推荐


















