Java获取本地IP,适用Windows和Linux

文章介绍了一种在Java中获取本地IP地址的通用方法,适用于Windows和Linux环境。通过遍历`NetworkInterface`获取所有网络接口,过滤出IPv4的非回环地址,从而得到本地IP。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近写了一个小功能,需要获取本地IP地址,直接用:InetAddress.getLocalHost().getHostAddress()来获取
Windows上能用,结果换到Linux环境不能使用,索性写个Windows和Linux通用的工具类
拿到所有的mac地址:NetworkInterface.getNetworkInterfaces();
然后去遍历所有的mac地址,取IPv4的地址(排除掉回环地址)
具体代码:

public static String getLocalIp() {
            InetAddress inetAddress = null;
            boolean isFind = false; // 返回标识
            Enumeration<NetworkInterface> networkInterfaceLists = null;
            try {
                // 获取网络接口
                networkInterfaceLists = (Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces();
            } catch (SocketException e) {
                e.printStackTrace();
            }
            while (networkInterfaceLists.hasMoreElements()) {
                NetworkInterface networkInterface = (NetworkInterface) networkInterfaceLists.nextElement();
                Enumeration<InetAddress> ips = networkInterface.getInetAddresses();
                // 遍历所有ip,获取本地地址中不是回环地址的ipv4地址
                while (ips.hasMoreElements()) {
                    inetAddress = (InetAddress) ips.nextElement();
                    if (inetAddress instanceof Inet4Address && inetAddress.isSiteLocalAddress()
                            && !inetAddress.isLoopbackAddress()) {
                        isFind = true;
                        break;
                    }
                }
                if (isFind) {
                    break;
                }
            }
            return inetAddress == null ? "" : inetAddress.getHostAddress();
        }

OK,完成!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值