IpUtils工具类

/**
 * <p>
 * Description: IP工具类
 * </p>
 *
 * @author songzixian
 * @version v2.0.0
 * @create 2023-06-18 21:41
 * @see com.songzixian.common.util
 */
public class IpUtils {
    /**
     * "unknown" 字符串常量
     */
    private static final String UNKNOWN = "unknown";

    /**
     * 检查 IP 地址是否未知
     *
     * @param ip
     * @return {@link boolean}
     */
    private static boolean isUnknown(String ip) {
        // 如果 IP 地址是 null、空字符串或 "unknown"(不区分大小写),那么返回 true,否则返回 false
        return ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip);
    }

    /**
     *
     * 获取有效的 IP 地址
     * @param  ips
     * @return {@link String}
     * @Date   2023/6/18
     */
    private static String getFirstValidIp(String ips) {
        // 如果 'ips' 不为空,那么尝试拆分 'ips' 并返回第一个非 "unknown" 的 IP 地址
        if (ips != null) {
            for (String ip : ips.split(",")) {
                if (!isUnknown(ip)) {
                    return ip;
                }
            }
        }
        return null;
    }

    /**
     * 获取 IP 地址
     * @param  request
     * @return {@link String}
     * @Date   2023/6/18
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ipAddress = null;

        // 定义一个数组,包含可能存储 IP 地址的 HTTP 头的名称,常见的情况是 'X-Forwarded-For'
        String[] headers = {"x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP"};

        // 遍历数组,尝试从每一个 HTTP 头获取 IP 地址
        for (String header : headers) {
            ipAddress = getFirstValidIp(request.getHeader(header));
            if (ipAddress != null) {
                // 如果找到了有效的 IP 地址,那么直接返回
                return ipAddress;
            }
        }

        // 如果没有找到有效的 IP 地址,那么尝试从 getRemoteAddr 获取 IP 地址
        ipAddress = request.getRemoteAddr();
        if (isUnknown(ipAddress)) {
            // 如果仍然没有找到有效的 IP 地址,那么尝试获取本地主机的 IP 地址
            try {
                ipAddress = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                // 如果无法获取本地主机的 IP 地址,那么抛出一个运行时异常
                throw new RuntimeException("无法获取本地主机的 IP 地址", e);
            }
        }

        return ipAddress;
    }

    /**
     * 解析ip地址 百度API
     *
     * @param ipAddress ip地址
     * @return 解析后的ip地址
     */
    public static String getIpBaiDuSource(String ipAddress) {
        try {
            URL url = new URL("http://opendata.baidu.com/api.php?query=" + ipAddress + "&co=&resource_id=6006&oe=utf8");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream(), "utf-8"));
            String line = null;
            StringBuffer result = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            Map map = JSON.parseObject(result.toString(), Map.class);
            List<Map<String, String>> data = (List) map.get("data");
            return data.get(0).get("location");
        } catch (Exception e) {
            return "";
        }
    }

}
Last modification:June 18, 2023
如果觉得这篇技术文章对你有用,请随意赞赏