Skip to main content

mycommon_utils/utils/
http_util.rs

1use std::net::IpAddr;
2use axum::extract::Request;
3use local_ip_address::{local_ip, Error};
4
5pub fn get_ip_addr(req: &Request) -> String {
6    let headers = req.headers();
7
8    // 从多个头部获取 IP 地址
9    let ip = headers.get("X-Forwarded-For")
10        .and_then(|value| value.to_str().ok())
11        .or_else(|| headers.get("Proxy-Client-IP").and_then(|value| value.to_str().ok()))
12        .or_else(|| headers.get("WL-Proxy-Client-IP").and_then(|value| value.to_str().ok()))
13        .or_else(|| headers.get("HTTP_CLIENT_IP").and_then(|value| value.to_str().ok()))
14        .or_else(|| headers.get("HTTP_X_FORWARDED_FOR").and_then(|value| value.to_str().ok()))
15        .unwrap_or_else(|| "unknown");
16
17    // 如果是本地地址,获取真实的本地 IP
18    if ip == "127.0.0.1" || ip == "::1" {
19        match get_local_ip() {
20            Ok(local_ip) => local_ip,
21            Err(_) => "unknown".to_string(),
22        }
23    } else {
24        ip.to_string()
25    }
26}
27
28fn get_local_ip() -> Result<String, Error> {
29    local_ip().map(|ip| match ip {
30        IpAddr::V4(v4) => v4.to_string(),
31        IpAddr::V6(v6) => v6.to_string(),
32    })
33}