用户下单 IP 获取指引
背景
用户下单 IP 获取方式
无代理场景
示例代码
public String getMcCreateTradeIp(HttpServletRequest request) {
String mc_create_trade_ip = "/";
if(!request.getRemoteAddr().equals("")){
mc_create_trade_ip = request.getRemoteAddr();
};
return mc_create_trade_ip;
}
function get_mcCreateTradeIp(){
mc_create_trade_ip = "/";
if ($_SERVER['REMOTE_ADDR']){
$mc_create_trade_ip = $_SERVER['REMOTE_ADDR']
}elseif (getenv("REMOTE_ADDR")){
$mc_create_trade_ip = getenv("REMOTE_ADDR");
}
return $mc_create_trade_ip;
}
注意事项
有代理场景

配置示例
nginx有代理情况配置
#修改default.conf配置文件
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-Port $remote_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
apache有代理情况配置
#修改httpd.conf文件
vi /usr/local/apache/conf/httpd.conf
Include conf/extra/httpd-remoteip.conf
# 加载mod_remoteip.so模块
LoadModule remoteip_module modules/mod_remoteip.so
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy <ip_range1><ip_range2> …… <ip_rangex>
示例代码
//获取请求头中的真实IP
public String getMcCreateTradeIp(HttpServletRequest request) {
//...其他逻辑
String mc_create_trade_ip = "/";
String mcProxyIp = "/";
String mcXffIp = "/";
if(!request.getRemoteAddr().equals("")){
mc_create_trade_ip = request.getRemoteAddr();//根据真实情况获取
};
if (!request.getHeader("X-Real-IP").equals("")){
mcProxyIp=request.getHeader("X-Real-IP");
mc_create_trade_ip = mcProxyIp;//根据真实情况获取
}else if(!request.getHeader("X-Forwarded-For").equals("")){
String[] mcXffIps = request.getHeader("X-Forwarded-For").split(",");
mc_create_trade_ip =mcXffIps[0];//根据真实情况获取
}else{
mc_create_trade_ip="/";
}
//...其他逻辑,根据真实情况获取真实IP
return mc_create_trade_ip;
}
案例说明
POST /test HTTP/1.1
Host: aaa.bb.cn
Cookie: xxxx
Content-Length: 1420
Cache-Control: max-age=0
Sec-Ch-Ua: " Not A;Brand";v="99", "Chromium";v="102", "Google Chrome";v="102"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Windows"
Upgrade-Insecure-Requests: 1
Origin: https://aaa.bb.cn
Content-Type: application/x-www-form-urlencoded
X-Forwarded-For: 120.24.169.223,8.8.8.8
Client-IP: 120.24.169.22
X-Client-IP: 120.24.169.22
X-Originating-IP: 120.24.169.22
X-Real-IP: 120.24.169.22
X-Remote-Addr: 120.24.169.22
X-Remote-IP: 120.24.169.22
User-Agent: Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: navigate
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate
Accept-Language: en,zh-CN;q=0.9,zh;q=0.8
Connection: close
修改于 2023-11-20 03:55:33