【问题标题】:Obtain IP Address from client's HTTP Request using Java [duplicate]使用Java从客户端的HTTP请求中获取IP地址[重复]
【发布时间】:2018-03-18 14:31:01
【问题描述】:

我在 Tomcat 7 上为 RESTful Web 服务使用 Spring 4 MVC。

想知道如果外部客户端发送 HTTP 请求,有没有办法在服务器端获取特定客户端的 IP 地址?

【问题讨论】:

  • 还要注意X-Forwarded-For 标头。
  • @Chrylis - 为什么我应该知道 X-Forwarded-For 标头?感谢您的预防措施。
  • 因为如果您在防火墙或负载平衡器后面(通常情况下),您从 HTTP 连接获得的 IP 地址将不是客户端的。
  • @PacificNW_Lover 你能通过接受答案来结束这个问题吗?如果你不这样做,它将保持开放,人们会认为你仍然需要帮助。

标签: java spring rest spring-mvc ip-address


【解决方案1】:
org.springframework.security.web.authentication.WebAuthenticationDetails

与 Web 身份验证请求相关的选定 HTTP 详细信息的持有者。

指示接收身份验证请求的 TCP/IP 地址。

String ipAddress = ((WebAuthenticationDetails)SecurityContextHolder.getContext().getAuthentication().getDetails()).getRemoteAddress();

如果您在本地应用程序上进行测试,您的 IP 地址将为 "0:0:0:0:0:0:0:1"

【讨论】:

    【解决方案2】:

    简单的 POJO

    public static InetAddress 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();  
        }  
        try {
            return InetAddress.getByName(ip);
        } catch (UnknownHostException e) {
            return null;
        }  
    }
    

    【讨论】:

    • 聪明,但不是很干。
    • 请指定UnknownHostException, rmi 或 net ?
    猜你喜欢
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 2013-03-19
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    相关资源
    最近更新 更多