java_获取客户端IP_根据IP地址获取计算机名字

/**
   * 获取客户端IP
   * @param request
   * @return
   */
  public static String getClientIP(javax.servlet.http.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.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getRemoteAddr();
	    }
	    return ip;
  }

 

	/**
  	 * 根据IP获取机器名
  	 * @param ip
  	 * @return
  	 */
	public static String getClientHostname(String ip) {
		InetAddress inetAddress;
		try {
			inetAddress = InetAddress.getByName(ip);
			String computername = inetAddress.getHostName();
			if (computername.equalsIgnoreCase("localhost")) {
				computername = InetAddress.getLocalHost().getCanonicalHostName();
			}
			return computername;
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return ip;
	}

 

你可能感兴趣的:(java_获取客户端IP_根据IP地址获取计算机名字)