獲取用戶ip指引
背景介紹
H5支付要求商戶在統(tǒng)一下單接口中上傳用戶真實(shí)ip地址“spbill_create_ip”,為保證微信端獲取的用戶ip地址與商戶端獲取的一致,提供了以下獲取用戶ip的指引,希望對(duì)大家有所幫助。
沒有代理的情況
在商戶的前端接入層沒有做代理的情況下獲取ip的方式比較簡(jiǎn)單,直接獲取'REMOTE_ADDR '即可。
代碼示例
function get_client_ip(){
$cip = "unknown";
if ($_SERVER['REMOTE_ADDR']){
$cip = $_SERVER['REMOTE_ADDR']
}elseif (getenv("REMOTE_ADDR")){
$cip = getenv("REMOTE_ADDR");
}
return $ip
}
有代理的情況
在有代理的情況下,因?yàn)橐婵蛻舳巳ピL問服務(wù)器,所以,當(dāng)請(qǐng)求包經(jīng)過反向代理后,在代理服務(wù)器這里這個(gè)IP數(shù)據(jù)包的IP包頭做了修改,最終后端WEB服務(wù)器得到的數(shù)據(jù)包的頭部源IP地址是代理服務(wù)器的IP地址。這樣一來,后端服務(wù)器的程序就無法獲取用戶的真實(shí)ip。
nginx有代理的情況:
在nginx中配置中加入
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有代理的情況:
vi /usr/local/apache/conf/httpd.conf
Include conf/extra/httpd-remoteip.conf
vi /usr/local/apache/conf/extra/httpd-remoteip.conf
LoadModule remoteip_module modules/mod_remoteip.so
RemoteIPHeader X-Forwarded-For
RemoteIPinternalProxy 127.0.0.1
代碼示例
string GetClientIp(CgiInput* poInput) {
string client_ip = "";
string strClientIPList;
GetHttpHeader("X-Forwarded-For", strClientIPList);
if (strClientIPList.empty()){
GetHttpHeader("X-Real-IP", strClientIPList);}
if (!strClientIPList.empty()){
size_t iPos = strClientIPList.find( "," );
if( iPos != std::string::npos ){
client_ip = strClientIPList.substr( iPos );}
else{
client_ip = strClientIPList;
}
}
if (client_ip.empty()){
GetHttpHeader("PROXY_FORWARDED_FOR", strClientIPList);
// 需進(jìn)行兼容
if(strClientIPList.empty()){
client_ip = getRemoteAddr();
}else{
size_t iPos = strClientIPList.find( "," );
if( iPos != std::string::npos ) {
client_ip = strClientIPList.substr( iPos );
}
else{
client_ip = strClientIPList;
}
}
}
if(!MMPayCommFunc::IsIp(client_ip))
client_ip = getRemoteAddr();
return client_ip;
}