Skip to main content

mycommon_utils/utils/
web_util.rs

1use axum::http::HeaderMap;
2
3
4pub fn get_remote_ip(header: HeaderMap) -> String {
5    let ip = match header.get("X-Forwarded-For") {
6        Some(x) => {
7            let mut ips = x.to_str().unwrap_or("").split(','); // 处理可能的 None
8            let ip = ips.next().unwrap_or("").trim().to_string();
9            if ip.is_empty() {
10                "Unknown".to_string()
11            } else {
12                ip
13            }
14        }
15        None => match header.get("X-Real-IP") {
16            Some(x) => {
17                let ip = x.to_str().unwrap_or("").to_string(); // 处理可能的 None
18                if ip.is_empty() {
19                    "Unknown".to_string()
20                } else {
21                    ip
22                }
23            }
24            None => {
25                // 如果没有代理,尝试从 remote_addr 获取 IP
26                header.get("remote_addr")
27                    .and_then(|x| x.to_str().ok())
28                    .unwrap_or("Unknown")
29                    .to_string()
30            }
31        },
32    };
33    ip
34}