package com.zzwtec.wechat.util.logger;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

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

/**
 * @Athor:xiezhongjiang
 * @Description:logback ipconvert
 * @Date:2017/10/30 10:31
 * @Since:1.0.0
 */
public class IpConvert extends ClassicConverter {
    public static String cacheIP;

    @Override
    public String convert(ILoggingEvent event) {
        try {
            if(cacheIP==null){
                InetAddress ia= InetAddress.getLocalHost();
                String localname = ia.getHostName();
                String localip = getIP(ia);
                cacheIP = localname + "|" + localip;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cacheIP;
    }

    public static String getIP(InetAddress address) {
        try {
            // 根据hostname找ip
            if (address.isLoopbackAddress()) {
                Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
                while (allNetInterfaces.hasMoreElements()) {
                    NetworkInterface netInterface = allNetInterfaces.nextElement();
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress ip = addresses.nextElement();
                        if (!ip.isLinkLocalAddress() && !ip.isLoopbackAddress() && ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
            return address.getHostAddress();
        } catch (SocketException e) {
            e.printStackTrace();
            return null;
        }
    }
}
