获取用户真实 IP 方法

一、获取用户ip

接入 CDN 后,为了方便获取客户端真实 IP,VeryCloud 贴心设计,在请求的头中添加 Cdn-Real-Ip 字段。

例:Cdn-Real-Ip: 58.214.233.214

需要注意的是这些代码是在您切换 CDN 后生效,如未使用 CDN 服务,这些代码是无法获得用户 IP 的。

下面是读取 Cdn-Real-ip 代码片段:

       php:

                  <?php                                                                   

                  $user_IP = ($_SERVER["HTTP_CDN_REAL_IP"]);                              

                  echo $user_IP;                                                          

                  ?>                                                                      

       Java:

                  String srcIp = request.getHeader("Cdn-Real-Ip");                        

                       if(srcIp == null){                                                 

                         srcIp = request.getRemoteAddr();                                 

                       }                                                                  

       [注]request 是 HttpServletRequest 类型的参数,无论是直接写 serverlet 还是用 struts 都会传入该参数

       Asp(用 C#):

                  String srcIp = Request.Headers["Cdn-Real-Ip"];                          

                  if(srcIp == null){                                                      

                                 srcIp = Request.UserHostAddress;                         

                           }                                                              

       ASP:

                  <% Request.ServerVariables("HTTP_Cdn-Real-Ip") %>