java 获取linux ip,如何通过Java获取Linux上的计算机的IP?

这篇博客提供了一个Java方法,用于在Linux系统中获取第一个非回环的IPv4或IPv6地址。该方法遍历所有网络接口,检查并排除回环地址,根据指定的IPv4或IPv6偏好返回相应的地址。当存在多个网络接口时,它将返回第一个非回环的IP。InetAddress类不适用于跨平台应用,因此这个解决方案更优。

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;

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值