使用Java获取发送请求的电脑的IP地址

介绍

客户端所有的请求信息都可以通过HttpServletRequest获得,获取客户端ip可以通过getRemoteAddr()获取。

但是如果客户端是通过代理访问我们的服务器,那么getRemoteAddr()获取到的ip就很有可能不是真实的ip,这时候我们可以通过请求头里的x-forwarded-for来获取真实的ip,请求每经一次代理,都会在后面拼接该代理的ip,以逗号分隔。

方法一:此方法获取真实IP(本机IP并不是127.0.0.1)

获取发送请求的电脑的IP地址,并返回

package com.lc.z.common.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

public class IpUtil {

    /**
     * 获取请求的ip
     */
    public static String getRequestIp() {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_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();
        }

        return ip;
    }
}

方法二:

RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
String clientIP = ServletUtil.getClientIP(request);
// 本地的服务输出 IP:127.0.0.1
System.out.println("IP:"+ clientIP);

你可能感兴趣的:(Java实践,java)