current position:Home>Utility gadget - get the IP address in the HTTP request

Utility gadget - get the IP address in the HTTP request

2022-04-29 15:43:34Lao Wang likes to knock the code


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

import static com.enn.common.constants.Constant.X_FORWARDED_FOR_UNKNOWN;

/**
 * @author wms
 * @date 2022/2/9
 */
public class IpAddressUtil {
    private static Logger LOGGER = LoggerFactory.getLogger(IpAddressUtil.class);
    public static final String X_FORWARDED_FOR_UNKNOWN = "unknown";
    /**
     *  obtain Ip Address 
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String xIp = request.getHeader("X-Real-IP");
        String xFor = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(xFor) && !X_FORWARDED_FOR_UNKNOWN.equalsIgnoreCase(xFor)) {
            // Be careful : Multiple agents will appear multiple times ip value , first ip Is real 
            int index = xFor.indexOf(",");
            if (index != -1) {
                String ip = xFor.substring(0, index);
                LOGGER.info("IpAddressUtil>>>getIpAddress>>>ip>>>{}",ip);
                return ip;
            } else {
                LOGGER.info("IpAddressUtil>>>getIpAddress>>>ip>>>{}",xFor);
                return xFor;
            }
        }
        xFor = xIp;
        if (StringUtils.isNotEmpty(xFor) && !X_FORWARDED_FOR_UNKNOWN.equalsIgnoreCase(xFor)) {
            return xFor;
        }
        if (StringUtils.isBlank(xFor) || X_FORWARDED_FOR_UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(xFor) || X_FORWARDED_FOR_UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(xFor) || X_FORWARDED_FOR_UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(xFor) || X_FORWARDED_FOR_UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(xFor) || X_FORWARDED_FOR_UNKNOWN.equalsIgnoreCase(xFor)) {
            xFor = request.getRemoteAddr();
        }
        LOGGER.info("IpAddressUtil>>>getIpAddress>>>ip>>>{}",xFor);
        return xFor;
    }
}

copyright notice
author[Lao Wang likes to knock the code],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291417359983.html

Random recommended