package com.qiaoba.common.web.util;

import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * IP工具类
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/25 15:49
 */
@Slf4j
public class IpUtil {

    private static Searcher searcher;

    public static void setSearcher(Searcher searcher) {
        IpUtil.searcher = searcher;
    }

    public static String getIp(HttpServletRequest request) {
        return ServletUtil.getClientIP(request);
    }

    public static String getIpAddr(String ip) {
        try {
            return searcher.search(ip);
        } catch (Exception e) {
            return "error ip";
        }
    }

    public static void closeSearcher() {
        try {
            searcher.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
