Finding user ip address

2019-01-22 02:54发布

问题:

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 user who all accessed the site. How can I find the IP address of user in JSF?

I tried with

    try {
        InetAddress thisIp = InetAddress.getLocalHost();
        System.out.println("My IP is  " + thisIp.getLocalHost().getHostAddress());
    } catch (Exception e) {
        System.out.println("exception in up addresss");
    }

however this gives me ip address of my site only i.e. server ip address.

Could someone tell me how to get IP address who accessed the website using Java?

回答1:

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);


回答2:

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;
}


回答3:

Try this...

HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();  
String ip = httpServletRequest.getRemoteAddr();