使用java获得所有IPv4
时间: 2024-02-07 19:41:01 浏览: 30
可以使用Java的NetworkInterface类来获取所有可用的网络接口,并通过NetworkInterface的getInetAddresses方法获取每个网络接口的IPv4地址。以下是一个示例代码:
```java
import java.net.*;
import java.util.*;
public class GetIPv4Addresses {
public static void main(String[] args) throws SocketException {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
if (addr instanceof Inet4Address) {
System.out.println(ni.getName() + ": " + addr.getHostAddress());
}
}
}
}
}
```
这个程序会输出类似以下的结果:
```
lo: 127.0.0.1
eth0: 192.168.0.100
```
其中,lo是本地回环接口(loopback interface)的名称,eth0是第一个以太网接口的名称,127.0.0.1是本地回环地址,192.168.0.100是第一个以太网接口的IPv4地址。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)