简体   繁体   English

如何确定HTTP和HTTPS请求中客户端的公共IP?

[英]How to determine public ip of client in HTTP and HTTPS request?

I have read various blogs and done practically but couldn't get conclusive and full proof way to determine the get client public ip in all possible scenarios. 我已经阅读了各种博客,并做了一些实际的工作,但是在所有可能的情况下,都无法获得确定性的完整证据来确定获取客户端公共IP的方法。 The configuration on server side is: | 服务器端的配置为: F5 <--> Apache web server <--> Tomcat | F5 <-> Apache Web服务器<-> Tomcat |

In code i first fetch and parse the request header X-FORWARDED-FOR to get the left most public ip. 在代码中,我首先获取并解析请求标头X-FORWARDED-FOR以获取最左边的公共ip。 If not found i rely on request.getRemoteAddr() . 如果找不到,我将依赖request.getRemoteAddr()

So question is: 所以问题是:

  1. This works well in some cases but fails when protocol is HTTPS. 在某些情况下,此方法效果很好,但在协议为HTTPS时失败。 What can be done in this case? 在这种情况下可以做什么?

  2. If the X-Forwarded-For doesn't have any value then i have to rely on request.getRemoteAddr() which always give my server ip. 如果X-Forwarded-For没有任何值,则我必须依赖request.getRemoteAddr() ,它始终为我的服务器提供IP。 This is because of apache web server which sits in between and getRemoteAddr returns the address of the client or last proxy that sent the request. 这是因为位于之间的apache Web服务器,而getRemoteAddr返回发送请求的客户端或最后一个代理的地址。 How to overcome this scenario? 如何克服这种情况?

  3. Is there any other headers on which i should read values apart from X-forwarded-for ? 除了X-forwarded-for外,我还应该读取其他任何标头吗?

  4. What all are the other possible cases which should be handled? 还有哪些其他可能的情况应该处理?

String forwardedHeader  = servletRequest.getHeader("X-Forwarded-For");
clientIP =  servletRequest.getRemoteAddr();    

String forwarded = "";
if (forwardedHeader != null && !forwardedHeader.isEmpty())
{
    forwarded = forwardedHeader;

    int commaIdx = forwarded.indexOf(',');
    if (commaIdx > 0)
    {
        clientIP = forwarded.substring(0, commaIdx);
    }

    forwarded = forwarded.replace(',', '|');
}

if (forwarded != null && !forwarded.isEmpty())
{
    clientIP = forwarded;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM