查找用户的IP地址(Finding user ip address)

2019-06-28 00:00发布

我创建使用JSF 2.0 Web应用程序。 我主持它托管网站和托管网站的服务器设在美国。

我的客户想要谁所有访问该网站的用户的详细信息。 我如何才能找到在JSF中的用户IP地址?

我试着用

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

然而,这给了我我的网站只有IE浏览器服务器的IP地址的IP地址。

有人能告诉我怎么去谁访问使用Java的网站的IP地址?

Answer 1:

我径自

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


Answer 2:

一个更灵活的解决方案

改进了接受的答案,即使有在多个 IP地址的作品版本X-Forwarded-For头:

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


Answer 3:

试试这个...

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


文章来源: Finding user ip address