查找用户IP地址

时间:2012-09-07 19:47:16

标签: jsf jsf-2 ip-address

我使用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地址吗?

3 个答案:

答案 0 :(得分:58)

我继续

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

答案 1 :(得分:12)

更通用的解决方案

即使X-Forwarded-For标题中有多个 IP地址,也可以使用已接受答案的改进版本:

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

答案 2 :(得分:4)

试试这个......

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