mycommon-utils 0.1.2

Common utilities library for database operations, Redis caching and system utilities
Documentation
use std::net::IpAddr;
use axum::extract::Request;
use local_ip_address::{local_ip, Error};

pub fn get_ip_addr(req: &Request) -> String {
    let headers = req.headers();

    // 从多个头部获取 IP 地址
    let ip = headers.get("X-Forwarded-For")
        .and_then(|value| value.to_str().ok())
        .or_else(|| headers.get("Proxy-Client-IP").and_then(|value| value.to_str().ok()))
        .or_else(|| headers.get("WL-Proxy-Client-IP").and_then(|value| value.to_str().ok()))
        .or_else(|| headers.get("HTTP_CLIENT_IP").and_then(|value| value.to_str().ok()))
        .or_else(|| headers.get("HTTP_X_FORWARDED_FOR").and_then(|value| value.to_str().ok()))
        .unwrap_or_else(|| "unknown");

    // 如果是本地地址,获取真实的本地 IP
    if ip == "127.0.0.1" || ip == "::1" {
        match get_local_ip() {
            Ok(local_ip) => local_ip,
            Err(_) => "unknown".to_string(),
        }
    } else {
        ip.to_string()
    }
}

fn get_local_ip() -> Result<String, Error> {
    local_ip().map(|ip| match ip {
        IpAddr::V4(v4) => v4.to_string(),
        IpAddr::V6(v6) => v6.to_string(),
    })
}