SoFunction
Updated on 2025-04-05

How to get the IP address of the computer that sent the request

introduce

All request information on the client can be obtained through HttpServletRequest, and the client ip can be obtained through getRemoteAddr().

However, if the client accesses our server through a proxy, then the ip obtained by getRemoteAddr() is likely not the real ip. At this time, we can obtain the real ip through the x-forwarded-for in the request header. Every time the proxy is requested, the ip of the proxy will be spliced ​​behind it, separated by commas.

Method 1

This method gets the real IP (native IP is not 127.0.0.1)

Get the IP address of the computer that sent the request and return

package ;

import ;
import ;

import ;

public class IpUtil {

    /**
      * Get the requested ip
      */
    public static String getRequestIp() {

        RequestAttributes requestAttributes = ();

        // Get the information of HttpServletRequest from Get RequestAttributes        HttpServletRequest request = (HttpServletRequest) (RequestAttributes.REFERENCE_REQUEST);

        String ip = ("x-forwarded-for");
        if (ip == null || () == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = ("Proxy-Client-IP");
        }
        if (ip == null || () == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = ("WL-Proxy-Client-IP");
        }
        if (ip == null || () == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = ("HTTP_CLIENT_IP");
        }
        if (ip == null || () == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = ("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || () == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = ();
        }

        return ip;
    }
}

Method 2

RequestAttributes requestAttributes = ();
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
String clientIP = (request);
// Local service output IP: 127.0.0.1("IP:"+ clientIP);

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.