获取客户端真实IP

客户端IP获取

获取客户端IP地址的方法是request.getRemoteAddr(),大部分情况下适用, 但如果用了代理和网关转发的情况下是获取不到客户端真实IP的,是代理请求服务器或网关的IP地址。

在我们使用nginx等反向代理软件时,不能通过这个方法获取客户端真实IP地址。

使用 X-Forwarded-For

要想获取真实IP地址,就要使用request.getHeader("x-forwarded-for")来获取

在请求头部中x-forwarded-for存的信息是:ip1,ip2,ip3,...,是代理服务器IP地址和客户端IP地址的相加

真正的客户端IP

x-forwarded-for中第一个非unknown的有效IP字符串。

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpUtil {
	private static final String UNKNOWN="unknown";
	private static final String LOCAL_IP="127.0.0.1";
	private static final String COMMA=",";
	private static final int FIFTEEN=15;
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (LOCAL_IP.equals(ipAddress)) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            //通过“,”分割IP,取出第一个IP,即为真实IP
            if (ipAddress != null && ipAddress.length() >FIFTEEN) { 
                if (ipAddress.indexOf(COMMA) > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
        }
        return ipAddress;
    }
}

参考:https://www.cnblogs.com/gne-hwz/p/9922301.html

你可能感兴趣的:(工具类,Java,tcp/ip,nginx,http)