查找用户的IP地址

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


2
你正在使用的方法是可行的,但它只能找到应用程序运行的IP地址,而不能找到用户的IP地址。 - Addicted
2
@Addicted:我知道那个……我在问题中提到了那个…… - Fahim Parkar
3个回答

64

我继续进行了

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

8
X-Forwarded-For 头部以逗号分隔的格式呈现。如果有的话,你只需要关注第一部分即可。请注意,不要改变原本的意思并尽量使翻译通俗易懂。 - BalusC
代理是否包含多个服务器?原因:我正在使用10.11.101.33作为代理,我的IP是10.11.33.102,但这段代码返回给我10.11.101.31。33是否首先为31提供服务?当没有代理时可以正常工作。 - Sarz
不适合测试,因为它依赖于FacesContext =*( - de.la.ru

19

更加灵活的解决方案

这是已被接受答案的改进版本,即使在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://dev59.com/qGct5IYBdhLWcg3wIqDW#38468051
 *
 * @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;
}

4
尝试一下这个...
HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();  
String ip = httpServletRequest.getRemoteAddr();  

8
如果客户端(或服务器)使用代理,这将失败。 - BalusC
1
@BalusC X-Forwarded-For(XFF)HTTP头是识别通过HTTP代理连接到Web服务器的客户端的原始IP地址的事实标准,但如果请求直接来自客户端,则可能返回null。另一个要点是,并不保证代理服务器会为您传递该标头。因此,标头为空并不一定意味着由getRemoteAddr返回的IP是发出原始请求的机器的实际IP。它仍然可能是代理服务器的IP。 - Kumar Vivek Mitra
5
我知道。你还没有根据这个修正你的答案。顺便问一下,为什么不用自己的话来表达呢?引用来源,而不是假装这是你自己的话。在SO上也可以看到cc-wiki许可证。 - BalusC
@BalusC...我本来想翻译的,但原作者写得太好了,我不想削弱它的精髓...在我准备在另一条评论中说这个之前..你要求了它...好吧..这是链接...http://www.coderanch.com/t/293684/JSP/java/client-IP-address-Domain-Java - Kumar Vivek Mitra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接