I. Overview
Get the client Ip tool class, support the case of proxy between client and server
two code
import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; /** * Get client ip */ public class IpUtil { private static final String[] CONTAINS_IP_HEADERS = { "X-Forwarded-For" , "Proxy-Client-IP" , "WL-Proxy-Client-IP" , "HTTP_CLIENT_IP" , "HTTP_X_FORWARDED_FOR" , "HTTP_X_FORWARDED" , "HTTP_X_CLUSTER_CLIENT_IP" , "HTTP_FORWARDED_FOR" , "HTTP_FORWARDED" ,"HTTP_VIA" ,"REMOTE_ADDR"}; /** * Get client ip * @param request http request * @return client ip (ipv4 or ipv6) */ public static String getClientIp(HttpServletRequest request) { String clientIp = getIpFromHttpHeader(request); if (StringUtils.isNotEmpty(clientIp)) { return clientIp; } return request.getRemoteAddr(); } //Get ip from http header for priority support with proxy private static String getIpFromHttpHeader(HttpServletRequest request) { for (String header : CONTAINS_IP_HEADERS) { String clientIps = request.getHeader(header); if (StringUtils.isEmpty(clientIps)) { continue; } if (StringUtils.equalsIgnoreCase("unknown", clientIps)) { continue; } //According to the proxy protocol, take the first one as the client ip if (!StringUtils.contains(clientIps, ",")) { return clientIps; } String[] ips = StringUtils.split(clientIps, ','); return ips[0]; } return null; } }