wangrong
2026-08-30 4c949c0dc9bcae785c281c9d8125295f09810b15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package io.dataease.utils;
 
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
 
import java.net.InetAddress;
import java.util.Arrays;
 
public class IPUtils {
 
    private static final String HEAD_KEYS = "x-forwarded-for, Proxy-Client-IP, WL-Proxy-Client-IP";
 
    private static final String UNKNOWN = "unknown";
 
    private static final String LOCAL_IP_KEY = "0:0:0:0:0:0:0:1";
    private static final String LOCAL_IP_VAL = "127.0.0.1";
 
    public static String get() {
 
        String ipStr = null;
        boolean isProxy = false;
 
        HttpServletRequest request = null;
        try {
            request = ServletUtils.request();
        } catch (Exception e) {
            LogUtil.error(e.getMessage(), e);
            return null;
        }
        if (ObjectUtils.isEmpty(request)) return null;
        String[] keyArr = HEAD_KEYS.split(",");
        for (String key : keyArr) {
            String header = request.getHeader(key.trim());
            if (StringUtils.isNotBlank(header) && !StringUtils.equalsIgnoreCase(UNKNOWN, header)) {
                ipStr = header;
                isProxy = true;
                break;
            }
        }
 
        if (!isProxy) {
            ipStr = request.getRemoteAddr();
        }
        ipStr = Arrays.stream(ipStr.split(",")).filter(item -> StringUtils.isNotBlank(item) && !StringUtils.equalsIgnoreCase(UNKNOWN, item.trim())).findFirst().orElse(ipStr);
        return StringUtils.equals(LOCAL_IP_KEY, ipStr) ? LOCAL_IP_VAL : ipStr;
    }
 
    public static String domain() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            return LOCAL_IP_VAL;
        }
    }
}