29

JSF2.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を使用してWebサイトにアクセスしたIPアドレスを取得する方法を教えてもらえますか?

4

3 に答える 3

63

私は先に進みました

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);
于 2012-09-08T07:21:53.733 に答える
19

より用途の広いソリューション

ヘッダーに複数のIPアドレスがある場合でも機能する、受け入れられた回答の改善されたバージョンX-Forwarded-For

/**
 * 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;
}
于 2016-07-19T20:36:23.603 に答える
4

これを試して...

HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();  
String ip = httpServletRequest.getRemoteAddr();  
于 2012-09-07T19:55:45.297 に答える