MCPcopy Create free account
hub / github.com/PlexPt/rocket-pt / IPUtils

Class IPUtils

src/main/java/com/rocketpt/server/util/IPUtils.java:15–97  ·  view source on GitHub ↗

获取请求主机IP地址工具 @author pt

Source from the content-addressed store, hash-verified

13 * @author pt
14 */
15@Slf4j
16public class IPUtils {
17
18 /**
19 * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址;
20 * <p>
21 * x-real-ip:171.111
22 * x-forwarded-for:171.1.157.11
23 * remote-host:171.111.157.11
24 * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
25 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
26 */
27 public static String getIpAddr() {
28
29 HttpServletRequest request =
30 ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
31
32
33 //打印头信息
34// Enumeration enums = request.getHeaderNames();
35// while (enums.hasMoreElements()) {
36// String headerName = (String) enums.nextElement();
37// String headerValue = request.getHeader(headerName);
38// log.info(headerName + ":" + headerValue);
39// }
40
41
42 return getIpAddr(request);
43 }
44
45 /**
46 * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址;
47 * <p>
48 * x-real-ip:171.111
49 * x-forwarded-for:171.1.157.11
50 * remote-host:171.111.157.11
51 * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
52 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
53 */
54 public static String getIpAddr(HttpServletRequest request) {
55
56 String ip = null;
57 try {
58 ip = request.getHeader("x-real-ip");
59
60
61 if (isUnknownIp(ip)) {
62 ip = request.getHeader("x-forwarded-for");
63
64 }
65 if (isUnknownIp(ip)) {
66 ip = request.getHeader("remote-host");
67 }
68 if (isUnknownIp(ip)) {
69 ip = request.getHeader("Proxy-Client-IP");
70
71 }
72 if (isUnknownIp(ip)) {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected