package com.starry.common.utils.ip;

import com.starry.common.utils.RegionUtils;
import com.starry.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * @author admin 获取地址工具类
 * @since 2022/7/25
 */
@Slf4j
public class AddressUtils {

    /**
     * 未知地址
     **/
    public static final String UNKNOWN = "XX XX";

    public static String getRealAddressByIp(String ip) {
        if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
            return "内网IP";
        }
        try {
            String rspStr = RegionUtils.getRegion(ip);
            if (StringUtils.isEmpty(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return UNKNOWN;
            }
            String[] obj = rspStr.split("\\|");
            String region = obj[2];
            String city = obj[3];
            return String.format("%s %s", region, city);
        } catch (Exception e) {
            log.error("获取地理位置异常", e);
        }
        return UNKNOWN;
    }
}
