How to get the ip of the computer on linux through Java ?
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.
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: I've used until now the InetAddress class which is a bad solution for cross-platform applications. (win/Linux).
解决方案
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系统中获取第一个非回环的IPv4或IPv6地址。该方法遍历所有网络接口,检查并排除回环地址,根据指定的IPv4或IPv6偏好返回相应的地址。当存在多个网络接口时,它将返回第一个非回环的IP。InetAddress类不适用于跨平台应用,因此这个解决方案更优。
347

被折叠的 条评论
为什么被折叠?



