從Http請求中獲取客戶端ip和端口java
import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; public final class InternetProtocol { private static Logger log = Logger.getLogger(InternetProtocol.class); /** * 構造函數. */ private InternetProtocol() { } /** * 獲取客戶端IP地址.<br> * 支持多級反向代理 * * @param request * HttpServletRequest * @return 客戶端真實IP地址 */ public static String getRemoteAddr(final HttpServletRequest request) { try{ String remoteAddr = request.getHeader("X-Forwarded-For"); // 若是經過多級反向代理,X-Forwarded-For的值不止一個,而是一串用逗號分隔的IP值,此時取X-Forwarded-For中第一個非unknown的有效IP字符串 if (isEffective(remoteAddr) && (remoteAddr.indexOf(",") > -1)) { String[] array = remoteAddr.split(","); for (String element : array) { if (isEffective(element)) { remoteAddr = element; break; } } } if (!isEffective(remoteAddr)) { remoteAddr = request.getHeader("X-Real-IP"); } if (!isEffective(remoteAddr)) { remoteAddr = request.getRemoteAddr(); } return remoteAddr; }catch(Exception e){ log.error("get romote ip error,error message:"+e.getMessage()); return ""; } } /** * 獲取客戶端源端口 * @param request * @return */ public static Long getRemotePort(final HttpServletRequest request){ try{ String port = request.getHeader("remote-port"); if( StringUtil.isNotEmptyString(port )) { try{ return Long.parseLong(port); }catch(NumberFormatException ex){ log.error("convert port to long error , port: "+port); return 0l; } }else{ return 0l; } }catch(Exception e){ log.error("get romote port error,error message:"+e.getMessage()); return 0l; } } /** * 遠程地址是否有效. * * @param remoteAddr * 遠程地址 * @return true表明遠程地址有效,false表明遠程地址無效 */ private static boolean isEffective(final String remoteAddr) { boolean isEffective = false; if ((null != remoteAddr) && (!"".equals(remoteAddr.trim())) && (!"unknown".equalsIgnoreCase(remoteAddr.trim()))) { isEffective = true; } return isEffective; } }