Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

background

During JavaWeb development, logs are recorded. During logging, the IP address of the client is stored. How to obtain the corresponding IP address of the client?

knowledge

The client access IP can be obtained through the Request object, the code is as follows, which is also the tool class I often use in the project.

Public class IPUtils {@param Request @return */ public static String getIpAddress(HttpServletRequest) request) { String ip = request.getHeader("x-forwarded-for"); System.out.println("x-forwarded-for ip: " + ip); if (ip ! = null && ip.length() ! = 0 &&!" Unknown ".equalsignorecase (IP)) {// If (ip.indexof (",")! =-1 ){ ip = ip.split(",")[0]; } } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); System.out.println("Proxy-Client-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); System.out.println("WL-Proxy-Client-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); System.out.println("HTTP_CLIENT_IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); System.out.println("X-Real-IP ip: " + ip); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); System.out.println("getRemoteAddr ip: " + ip); } system.out. println(" get client IP: "+ IP); return ip; }}Copy the code

You can call this utility class to get the IP address currently accessed by the client.

A special case

There are also special cases where the client may invoke the back-end code by proxy, so the IP may not actually be the real address.

In addition, if forwarding is used, the IP may be obtained differently.

So don’t rely too much on it when you’re using IP capture.