package cn.com.capcloud.core.util;

import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Author LiaoJiaHui
 * @Create 2024/9/5 9:24
 */
@Component
public class IPSearcher {
    @Value("${rzth.ipXdbFilePath}")
    private String ipXdbFilePath;
    private static Searcher searcher=null;
    public String getIP(String ip){
        if(searcher==null){
            byte[] cBuff;
            try {
                cBuff = Searcher.loadContentFromFile(ipXdbFilePath);
            } catch (Exception e) {
                return "";
            }
            try {
                searcher = Searcher.newWithBuffer(cBuff);
            } catch (Exception e) {
                return "";
            }
        }
        if(ip.equals("127.0.0.1")){
            return "内网|本地";
        }
        String region = null;
        try {
            region = searcher.search(ip);
            // 将"|0"替换掉
            String result = region.replace("|0","");
            return result;
        } catch (Exception e) {
            return "未知";
        }
    }
}
