package vip.xiaonuo.coldchain.core.renke.util;

/**
 * @author jackzhou
 * @version 1.0
 * @project jfcloud-coldchain
 * @description
 * @date 2024/11/1 15:43:20
 */

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

@Slf4j
@UtilityClass
public class IPUtil {
    public static String getIp() {
        String ip = getLocalIp();
        if (ip == null || "".equals(ip)) {
            ip = getLocalIp2();
        }
        return ip;
    }

    private static String getLocalIp() {
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements()) {
                NetworkInterface networkInterface = en.nextElement();
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (!address.isLoopbackAddress() && !address.isLinkLocalAddress() && !address.isSiteLocalAddress()) {
                        String ipAddress = address.getHostAddress();
                        log.info("获取到的IP为【{}】", ipAddress);
                        return ipAddress;
                    }
                }
            }
        } catch (Exception e) {
            log.error("getLocalIP1 获取IP报错", e);
        }
        return null;
    }

    public static String getLocalIp2() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            log.error("getLocalIp2 获取IP报错", e);
        }
        return null;
    }

}