29

我已经使用 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");
    }

但是,这仅给了我站点的 IP 地址,即服务器 IP 地址。

有人可以告诉我如何获取使用 Java 访问该网站的 IP 地址吗?

4

3 回答 3

63

我继续前进

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);
于 2012-09-08T07:21:53.733 回答
19

更通用的解决方案

即使标头中有多个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;
}
于 2016-07-19T20:36:23.603 回答
4

尝试这个...

HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();  
String ip = httpServletRequest.getRemoteAddr();  
于 2012-09-07T19:55:45.297 回答