Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine by what IP Address my website has been accessed? [duplicate]

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.

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

like image 306
Prateek Avatar asked Aug 24 '12 10:08

Prateek


2 Answers

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

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

There's one caution for using the method getRemoteAddr:

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").

An example usage in JSP:

Use set value of IP address in session using 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.

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

Please read docs:

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

like image 114
kapandron Avatar answered Oct 05 '22 04:10

kapandron


Along with the above said answers (by Andrey and Stephen) do use some analytics tool also. It will give you a bigger picture of the traffic coming to your website. One such example is Google Analytics.

like image 41
pratikabu Avatar answered Oct 05 '22 04:10

pratikabu