1 package com.sunll.common.util; 2 3 import javax.servlet.http.HttpServletRequest; 4 import java.io.IOException; 5 6 /** 7 * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址; 8 * 9 */ 10 public class NetworkUtil { 11 12 public final static String getIpAddress(HttpServletRequest request) { 13 // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 14 String ip = request.getHeader("X-Forwarded-For"); 15 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 16 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 17 ip = request.getHeader("Proxy-Client-IP"); 18 } 19 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 20 ip = request.getHeader("WL-Proxy-Client-IP"); 21 } 22 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 23 ip = request.getHeader("HTTP_CLIENT_IP"); 24 } 25 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 26 ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 27 } 28 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 29 ip = request.getRemoteAddr(); 30 } 31 32 //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 33 } else if (ip.length() > 15) {//"***.***.***.***".length() = 15 34 String[] ips = ip.split(","); 35 for (int index = 0; index < ips.length; index++) { 36 String strIp = ips[index]; 37 if (!("unknown".equalsIgnoreCase(strIp))) { 38 ip = strIp; 39 break; 40 } 41 } 42 } 43 return ip; 44 } 45 }