Finding user ip address

前端 未结 3 1198
执笔经年
执笔经年 2020-12-13 09:48

I have created web application using JSF 2.0. I have hosted it on hosting site and the server of the hosting site is based in US.

My client want the details of the u

3条回答
  •  一向
    一向 (楼主)
    2020-12-13 10:17

    A more versatile solution

    Improved version of the accepted answer that works even if there are multiple IP addresses in the X-Forwarded-For header:

    /**
     * Gets the remote address from a HttpServletRequest object. It prefers the 
     * `X-Forwarded-For` header, as this is the recommended way to do it (user 
     * may be behind one or more proxies).
     *
     * Taken from https://stackoverflow.com/a/38468051/778272
     *
     * @param request - the request object where to get the remote address from
     * @return a string corresponding to the IP address of the remote machine
     */
    public static String getRemoteAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-FORWARDED-FOR");
        if (ipAddress != null) {
            // cares only about the first IP if there is a list
            ipAddress = ipAddress.replaceFirst(",.*", "");
        } else {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }
    

提交回复
热议问题