First, get the IP and directly upload the code
import ; import ; import ; import ; import ; /** * Get IP address tool class */ public final class IpUtil { private static final String UNKNOWN = "unknown"; private static final String IPV6_LOCAL = "::1"; // Recommended compression private IpUtil(){ throw new AssertionError(); } /** * Get the IP address of the requesting user * @return */ public static String getRequestIp() { ServletRequestAttributes attributes = (ServletRequestAttributes) (); HttpServletRequest request = (); return getRequestIp(request); } /** * Get the IP address of the requesting user * @param request * @return */ public static String getRequestIp(HttpServletRequest request) { String ip = ("x-forwarded-for"); // Process multi-level proxy to obtain the first non-unknown valid IP if (ip != null && !() && !(ip)) { ip = (",")[0].trim(); // Get the first IP } else { ip = ("X-Real-IP"); // Commonly used in Nginx proxy } // Alternative solution: Try to get from other headers if (ip == null || () || (ip)) { ip = ("Proxy-Client-IP"); } if (ip == null || () || (ip)) { ip = ("WL-Proxy-Client-IP"); } if (ip == null || () || (ip)) { ip = (); // Get the remote address by default } // If it is a local loopback address, it returns the IP of the local machine if (IPV6_LOCAL.equals(ip) || "127.0.0.1".equals(ip)) { ip = getLocalhostIp(); // Get local IP } return ip; } private static String getLocalhostIp() { try { InetAddress inetAddress = (); return (); } catch (UnknownHostException e) { (); return "127.0.0.1"; // If it cannot be retrieved, return the loopback address } } }
But today I found a problem. All addresses are displayed as 127.0.0.1. I thought it should be caused by nginx agent, so I added the following configuration to nginx
server { listen 80; server_name ; location / { # Forward the real IP of the client proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; # Proxy forwards requests to gateway service proxy_pass http://localhost:1000/; } }
After restarting nginx, you will get the real IP address again (note that the so-called real IP is not necessarily true, this thing can be forged. As for the prevention measures, everyone will search for it yourself. The path is one foot high and the devil is one foot high)
This is the end of this article about using Java to obtain client IP addresses. For more related content on Java to obtain client IP addresses, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!