Java如何从接口里获取IP
时间: 2024-06-13 12:07:47 浏览: 146
Java可以通过以下代码从接口中获取IP地址:
```java
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class GetIPAddress {
public static void main(String[] args) {
try {
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.isLinkLocalAddress() && !addr.isLoopbackAddress() && addr.isSiteLocalAddress()) {
System.out.println("IP地址:" + addr.getHostAddress());
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}
```
这段代码会遍历所有的网络接口,然后获取每个接口的IP地址。在获取IP地址时,会过滤掉回环地址和链路本地地址,只输出站点本地地址。
阅读全文