Finding user ip address

前端 未结 3 1195
执笔经年
执笔经年 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:16

    Try this...

    HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();  
    String ip = httpServletRequest.getRemoteAddr();  
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-13 10:18

    I went ahead with

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }
    System.out.println("ipAddress:" + ipAddress);
    
    0 讨论(0)
提交回复
热议问题