|
| 1 | +package com.macro.mall.common.util; |
| 2 | + |
| 3 | +import javax.servlet.http.HttpServletRequest; |
| 4 | +import java.net.InetAddress; |
| 5 | +import java.net.UnknownHostException; |
| 6 | + |
| 7 | +/** |
| 8 | + * 请求工具类 |
| 9 | + * Created by macro on 2020/10/8. |
| 10 | + */ |
| 11 | +public class RequestUtil { |
| 12 | + |
| 13 | + /** |
| 14 | + * 获取请求真实IP地址 |
| 15 | + */ |
| 16 | + public static String getRequestIp(HttpServletRequest request) { |
| 17 | + //通过HTTP代理服务器转发时添加 |
| 18 | + String ipAddress = request.getHeader("x-forwarded-for"); |
| 19 | + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { |
| 20 | + ipAddress = request.getHeader("Proxy-Client-IP"); |
| 21 | + } |
| 22 | + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { |
| 23 | + ipAddress = request.getHeader("WL-Proxy-Client-IP"); |
| 24 | + } |
| 25 | + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { |
| 26 | + ipAddress = request.getRemoteAddr(); |
| 27 | + // 从本地访问时根据网卡取本机配置的IP |
| 28 | + if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) { |
| 29 | + InetAddress inetAddress = null; |
| 30 | + try { |
| 31 | + inetAddress = InetAddress.getLocalHost(); |
| 32 | + } catch (UnknownHostException e) { |
| 33 | + e.printStackTrace(); |
| 34 | + } |
| 35 | + ipAddress = inetAddress.getHostAddress(); |
| 36 | + } |
| 37 | + } |
| 38 | + // 通过多个代理转发的情况,第一个IP为客户端真实IP,多个IP会按照','分割 |
| 39 | + if (ipAddress != null && ipAddress.length() > 15) { |
| 40 | + if (ipAddress.indexOf(",") > 0) { |
| 41 | + ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); |
| 42 | + } |
| 43 | + } |
| 44 | + return ipAddress; |
| 45 | + } |
| 46 | + |
| 47 | +} |
0 commit comments