java获取本机网卡ip地址
时间: 2023-08-14 07:06:19 浏览: 125
要获取本机网卡的IP地址,你可以使用Java的`NetworkInterface`类。下面是一个示例代码,它可以获取本机所有网卡的IP地址:
```java
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class Main {
public static void main(String[] args) {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().indexOf(":") == -1) {
System.out.println("网卡名称: " + networkInterface.getDisplayName());
System.out.println("IP地址: " + inetAddress.getHostAddress());
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}
```
这段代码会遍历所有的网络接口,然后获取每个接口的所有IP地址。注意,过滤掉了回环地址和IPv6地址。运行代码后,你将会得到每个网卡的名称和对应的IP地址。
阅读全文