Поиск IP-адреса пользователя
Я создал веб-приложение с использованием JSF 2.0. Я разместил его на сайте хостинга, а сервер хостинг-сайта базируется в США.
Мой клиент хочет получить информацию о пользователе, который получил доступ к сайту. Как найти IP-адрес пользователя в JSF?
Я пробовал с помощью
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-адрес моего сайта только i.e. ip-адрес сервера.
Может ли кто-нибудь сказать мне, как получить IP-адрес, который обратился к веб-сайту с помощью Java?
Ответы
Ответ 1
Я пошел вперед с
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);
Ответ 2
Более универсальное решение
Улучшенная версия принятого ответа, которая работает, даже если в заголовке 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;
}
Ответ 3
Попробуйте это...
HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String ip = httpServletRequest.getRemoteAddr();