如何确定访问我的网站的IP地址? [英] How to determine by what IP Address my website has been accessed?

查看:121
本文介绍了如何确定访问我的网站的IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web应用程序,为此我想捕获访问我的网站的客户端的IP地址,以便我可以知道访问该应用程序的区域最多。我在我的应用程序中使用 Java EE

I have a web application and for that I want to capture the IP address of the clients who are accessing my website so that I can know what region is the most accessing the application. I am using Java EE in my application.

如果我们谈论标题和何时,可能会有一些解决方案code>请求从最终用户发送。

Probably there is some solution if we talk about header and when request is sent from the end-user.

推荐答案

使用方法 getRemoteAddr() http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html =noreferrer> ServletRequest 或方法 getHeaders()表单接口 HttpServletRequest

Use method getRemoteAddr() from interface ServletRequest or methods getHeaders() form interface HttpServletRequest:

HttpServletRequest httpRequest = (HttpServletRequest) request;
String userIpAddress = httpRequest.getHeader("X-Forwarded-For");

使用方法时有一个注意事项 getRemoteAddr

There's one caution for using the method getRemoteAddr:

当然可以使用方法,一般情况下,您将获得客户端的IP。但是,如果用户位于代理后面,则该方法无用。在这种情况下,您将获得代理服务器的IP地址,而不是客户端。但代理可能在特殊的 HTTP 标头中包含请求客户端IP。所以要检索真实客户端IP调用方法 getHeader(X-Forwarded-For)

Sure you can use the method and in general case you will get IP of client. However, the method is useless if an user is behind a proxy. In this case you'll get the proxy server's IP address and not the client. But the proxy may include the requesting client IP in a special HTTP header. So to retrieve real-client-IP call method getHeader("X-Forwarded-For").

JSP中的示例用法:

使用 JSTL

<c:set var="userIp" value="${requestScope.header('x-forwarded-for')}" scope="session" />

然后在方便的地方从会话中获取此值。

And then get this value from the session in a convenient place.

在JSP中,您可以使用< c:out value =$ {sessionScope.userIp}/> 或在servlet中使用 session.getAttribute('userIp');

In JSP you can use <c:out value="${sessionScope.userIp}" /> or in servlet as session.getAttribute('userIp');

请阅读 docs


java.lang.String getRemoteAddr()返回客户端的Internet协议(IP)地址或发送请求的最后一个代理

java.lang.String getRemoteAddr() returns the Internet Protocol (IP) address of the client or last proxy that sent the request.

这篇关于如何确定访问我的网站的IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆