获取当前系统ip linux也适用

package cn.exrick.xboot.common.utils;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.env.EnvironmentPostProcessor;

import org.springframework.core.env.ConfigurableEnvironment;

import java.net.*;

import java.util.Enumeration;

public class GetIp implements EnvironmentPostProcessor {

    @Override

    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

        String logFilePath = environment.getProperty("logging.file.path");

        String ipAddr = "";

        InetAddress addr = getLocalHostExactAddress();

        ipAddr = addr.getHostAddress();

        environment.getSystemProperties().put("logging.file.path", logFilePath + ipAddr);

    }

    private InetAddress getLocalHostExactAddress() {

        try {

            InetAddress candidateAddress = null;

   Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

            while (networkInterfaces.hasMoreElements()) {

                NetworkInterface iface = networkInterfaces.nextElement();

                // 该网卡接口下的ip会有多个,也需要一个个的遍历,找到自己所需要的

                for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {

                    InetAddress inetAddr = inetAddrs.nextElement();

                    // 排除loopback回环类型地址(不管是IPv4还是IPv6 只要是回环地址都会返回true)

                    if (!inetAddr.isLoopbackAddress()) {

                        if (inetAddr.isSiteLocalAddress()) {

                            // 如果是site-local地址,就是它了 就是我们要找的

                            // ~~~~~~~~~~~~~绝大部分情况下都会在此处返回你的ip地址值~~~~~~~~~~~~~

                            return inetAddr;

                        }

                        // 若不是site-local地址 那就记录下该地址当作候选

                        if (candidateAddress == null) {

                            candidateAddress = inetAddr;

                        }

                    }

                }

            }

            // 如果出去loopback回环地之外无其它地址了,那就回退到原始方案吧

            return candidateAddress == null ? InetAddress.getLocalHost() : candidateAddress;

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

}

在sources下创建META_INF/spring.factories文件   文件内容是要加载的bean对象  例:

org.springframework.boot.env.EnvironmentPostProcessor=\

cn.exrick.xboot.common.utils.GetIp

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值