How do I get the remote address of a client in servlet?

前端 未结 10 1885
刺人心
刺人心 2020-11-22 07:32

Is there any way that I could get the original IP address of the client coming to the server? I can use request.getRemoteAddr(), but I always seem to get the IP

相关标签:
10条回答
  • 2020-11-22 08:14

    As this is usually a deployment concern, rather than an application concern, another approach would be to configure the application container appropriately. Once configured, the container takes care of inspecting the appropriate header and your application continues to use request.getRemoteAddr().

    For example, in Tomcat you can use the Remote IP Valve. I would assume most application servers have similar functionality.

    The container could also take care of understanding if your front-end load balancer is terminating SSL connections, forwarding the request to the app server over HTTP. This is important when your application needs to generate URLs to itself.

    0 讨论(0)
  • 2020-11-22 08:18
    InetAddress inetAddress = InetAddress.getLocalHost();
    String ip = inetAddress.getHostAddress();
    
    0 讨论(0)
  • 2020-11-22 08:20
    String ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null) {
                ipAddress = request.getHeader("X_FORWARDED_FOR");
                if (ipAddress == null){
                    ipAddress = request.getRemoteAddr();
                }
            }
    
    0 讨论(0)
  • 2020-11-22 08:26

    You cannot do this in a meaningful way.

    The proxy may or may not add a proxied-for header, but in many cases this will be an internal only address anyway, so it will be meaningless to you. Most proxies at the edge of an organization are configured to reveal as little as possible about the internals of the network anyway.

    What are you intending to use this information for?

    0 讨论(0)
提交回复
热议问题