如何通过Java获取Linux上的计算机的IP? [英] How to get the ip of the computer on linux through Java?
问题描述
如何通过Java获取Linux上的计算机的ip?
How to get the ip of the computer on linux through Java ?
我在网上搜索了一些例子,我发现了一些关于NetworkInterface类的内容,但我无法理解我是如何得到IP地址的。
I searched the net for examples, I found something regarding NetworkInterface class, but I can't wrap my head around how I get the Ip address.
如果我同时运行多个网络接口会怎样?将返回哪个IP地址。
What happens if I have multiple network interfaces running in the same time ? Which Ip address will be returned.
我非常感谢一些代码示例。
I would really appreciate some code samples.
PS:我是直到现在使用的InetAddress类对于跨平台应用程序来说是一个糟糕的解决方案。 (win / Linux)。
P.S: I've used until now the InetAddress class which is a bad solution for cross-platform applications. (win/Linux).
推荐答案
不要忘记在外面看不到的环回地址。这是一个提取第一个非环回IP(IPv4或IPv6)的函数
Do not forget about loopback addresses, which are not visible outside. Here is a function which extracts the first non-loopback IP(IPv4 or 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获取Linux上的计算机的IP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!