问题描述
如何通过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.
P.S:到目前为止,我一直使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!