Web端获取访问者IP

来源:互联网 发布:买火车票的软件 编辑:程序博客网 时间:2024/06/05 03:37

实际开发过程中,服务器后台需要知道访问者ip,此时我们需要获取ip并记录。

HTTP header 中的 Host 含义为所请求的目的主机名。HTTP header 中的 X_Forward_For 表示该条 http 请求是由谁发起的,即是我们需要获取的访问者IP。

建立工具类,java端代码:

public class IPUtils {    /**     * 获取访问者IP     *      * HTTP header中的X_Forward_For表示该条http请求是由谁发起的,即是访问者IP     *      * 在一般情况下使用Request.getRemoteAddr()即可,但是经过nginx等反向代理软件后,这个方法会失效,获取的是nginx地址。     *      * Request.getRemoteAddr()实际上是获取的$remote_addr,$remote_addr是nginx的导出变量,可在nginx.conf中直接使用     *      * 那么则可以在离用户最近的前端代理nginx上获取X_Forward_For,将其存放于$remote_addr中,此时在web端使用Request.getRemoteAddr()直接获取访问者IP     *      * 具体配置:     * proxy_set_header Host $host;     * proxy_set_header X-Forward-For $remote_addr;     *      * @param request     * @return     */    public static String getIpAddr(HttpServletRequest request) {        String ip = request.getHeader("X-Forward-For");          if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {              ip = request.getHeader("Proxy-Client-IP");          }          if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {              ip = request.getHeader("WL-Proxy-Client-IP");          }          if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {              ip = request.getRemoteAddr();          }          return ip;      }}

nginx配置:

location / {    proxy_pass http://localhost:8080/mate/; # 转发请求到tomcat下mate项目    proxy_set_header Host $host; # 避免http请求中丢失Host头部时Host不被重写    proxy_set_header X-Forward-For $remote_addr; # 获取http请求的ip值存储到$remote_addr}

以上proxy_pass配置请自动忽略,与本实例无关。

更多参考:https://yq.aliyun.com/articles/42168