使用Java从客户端的HTTP请求获取IP地址

时间:2017-10-06 18:06:39

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

在Tomcat 7上使用Spring 4 MVC进行RESTful Web服务。

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

2 个答案:

答案 0 :(得分:0)

简单的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;
    }  
}

答案 1 :(得分:0)

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"