1. 程式人生 > >java獲取真實的客戶端ip,用java後臺獲取ip地址

java獲取真實的客戶端ip,用java後臺獲取ip地址

// 獲取客戶端ip
public static String getClientIp(HttpServletRequest request) {
   String ip = request.getHeader("x-forwarded-for");
   if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
   }
   if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
   }
   if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
   }
   if (ip == null || ip.length() == 0 || ip.indexOf(":") > -1) {
      try {
         ip = InetAddress.getLocalHost().getHostAddress();
      } catch (UnknownHostException e) {
         ip = null;
      }
   }
   return ip;
}