如何在servlet中获取客户端的远程地址?


71

有什么办法可以使客户机获得服务器的原始IP地址?我可以使用request.getRemoteAddr(),但我似乎总能获得代理服务器或Web服务器的IP。

我想知道客户端用来连接我的IP地址。无论如何,我能得到吗?

Answers:


111

尝试这个:

public static String getClientIpAddr(HttpServletRequest request) {  
        String ip = request.getHeader("X-Forwarded-For");  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_CLIENT_IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        }  
        return ip;  
    }  

在这种情况下,可以使用if conditiona代替if / else吗?
安德鲁

1
是的,因为我们需要检查先前的操作是否成功,也许使用do-while会更好
Fareed Alnamrouti 2013年

4
X-Forwarded-For可以包含多个IP地址。
dmatej '17

10

request.getRemoteAddr()就是这样。看来您的代理更改了源IP。当某些代理这样做时,它们会在某些自定义http标头中添加原始IP。使用request.getHeaderNames()request.getHeaders(name)打印所有内容,以查看是否没有感兴趣的内容。赞X-CLIENT-IP(制作一个,但看起来像这样)


谢谢,我将检查标头...。虽然例如,当它通过网络服务器时,我会获得网络服务器地址
grassbl8d 2011年

2
您的意思是request.getHeaderNames()吗?
uv

5

我用过的最好的解决方案

public String getIpAddr(HttpServletRequest request) {      
   String ip = request.getHeader("x-forwarded-for");      
   if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
       ip = request.getHeader("Proxy-Client-IP");      
   }      
   if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
       ip = request.getHeader("WL-Proxy-Client-IP");      
   }      
   if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
       ip = request.getRemoteAddr();      
   }      
   return ip;      
} 

5

由于这通常是部署问题,而不是应用程序问题,因此另一种方法是适当地配置应用程序容器。配置完成后,容器将负责检查适当的标头,并且您的应用程序将继续使用request.getRemoteAddr()

例如,在Tomcat中,您可以使用Remote IP Valve。我假设大多数应用程序服务器具有类似的功能。

容器还可以帮助您了解前端负载均衡器是否正在终止SSL连接,并通过HTTP将请求转发至应用服务器。当您的应用程序需要为其自身生成URL时,这一点很重要。


3

您无法以有意义的方式执行此操作。

代理可以添加也可以不添加代理标头,但是在许多情况下,无论如何这都是内部唯一的地址,因此对您而言毫无意义。无论如何,组织边缘的大多数代理都配置为尽可能少地揭示网络内部。

您打算将这些信息用于什么?


好吧,我有点需要记录正在访问的用户的地址。您是对的,有些代理似乎已将其删除,并且我经常用代理替换它....我在想,也许我可以从SSL会话中获取一些信息
grassbl8d 2011年

3

为什么不使用这样更优雅的解决方案?

private static final List<String> IP_HEADERS = Arrays.asList("X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR");

public static String getClientIpAddr(HttpServletRequest request) {
    return IP_HEADERS.stream()
        .map(request::getHeader)
        .filter(Objects::nonNull)
        .filter(ip -> !ip.isEmpty() && !ip.equalsIgnoreCase("unknown"))
        .findFirst()
        .orElseGet(request::getRemoteAddr);
}

重复删除您的代码!



0
String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null) {
            ipAddress = request.getHeader("X_FORWARDED_FOR");
            if (ipAddress == null){
                ipAddress = request.getRemoteAddr();
            }
        }

0

为什么我认为我们应该首先尝试从标题“ X-Forwarded-For”获取IP ?如果您来自request.getRemoteAddr(),则可能是客户端的真实IP或转发请求的最后一个代理的IP。因此,我们无法确定它属于哪个条件。但是,如果在标头中设置了' X-Forwarded-For',则客户端ip必定是从其获得的内容的最左侧部分。

    /**
     * Try to get real ip from request:
     * <ul>
     *     <li>try X-Forwarded-For</li>
     *     <li>try remote address</li>
     * </ul>
     *
     * @param request    request
     * @return real ip or ""
     */
    private String tryGetRealIp(HttpServletRequest request) {
        // X-Forwarded-For: <client>, <proxy1>, <proxy2>
        // If a request goes through multiple proxies, the IP addresses of each successive proxy is listed.
        // This means, the right-most IP address is the IP address of the most recent proxy and
        // the left-most IP address is the IP address of the originating client.
        String forwards = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotBlank(forwards)) {
            // The left-most IP must be client ip
            String ip = StringUtils.substringBefore(forwards, ",");
            return ip;
        } else if (StringUtils.isNotBlank(request.getRemoteAddr())) {
            // this could be real client ip or last proxy ip which forwards the request
            return request.getRemoteAddr();
        }
        return "";
    }

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.