如何通过Java在Linux上获取计算机的IP?
2022-09-04 23:52:05
如何通过Java在Linux上获取计算机的IP?
我在网上搜索了一些例子,我发现了一些关于NetworkInterface类的东西,但我无法理解我如何获得IP地址。
如果我同时运行多个网络接口,会发生什么情况?将返回哪个 IP 地址。
我真的很感激一些代码示例。
P.S:到目前为止,我一直使用InetAddress类,这对于跨平台应用程序来说是一个糟糕的解决方案。(win/Linux)。
如何通过Java在Linux上获取计算机的IP?
我在网上搜索了一些例子,我发现了一些关于NetworkInterface类的东西,但我无法理解我如何获得IP地址。
如果我同时运行多个网络接口,会发生什么情况?将返回哪个 IP 地址。
我真的很感激一些代码示例。
P.S:到目前为止,我一直使用InetAddress类,这对于跨平台应用程序来说是一个糟糕的解决方案。(win/Linux)。
不要忘记环回地址,它们在外面不可见。下面是一个提取第一个非环回 IP(IPv4 或 IPv6)的函数
private static InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6) throws SocketException {
Enumeration en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface i = (NetworkInterface) en.nextElement();
for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr = (InetAddress) en2.nextElement();
if (!addr.isLoopbackAddress()) {
if (addr instanceof Inet4Address) {
if (preferIPv6) {
continue;
}
return addr;
}
if (addr instanceof Inet6Address) {
if (preferIpv4) {
continue;
}
return addr;
}
}
}
}
return null;
}
从 Java 教程
为什么不是一个好的解决方案?我在文档中没有看到任何有关跨平台兼容性的内容?InetAddress
此代码将枚举所有网络接口并检索其信息。
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
public class ListNets
{
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("\n");
}
}
以下是示例程序的示例输出:
Display name: bge0
Name: bge0
InetAddress: /fe80:0:0:0:203:baff:fef2:e99d%2
InetAddress: /121.153.225.59
Display name: lo0
Name: lo0
InetAddress: /0:0:0:0:0:0:0:1%1
InetAddress: /127.0.0.1