101
技术社区[云栖]
从http协议中获得客户端ip
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;
}
}
最后更新:2017-06-05 16:01:45
上一篇:
“无中生有”计算机视觉探奇
下一篇:
周末读物|当你改变世界却没有人注意
POJ1061 扩展欧几里得
北大团队研发“车脸”识别系统,不看车牌看外观特征实现精确识别
图片的赖加载(lazyLoad)
数据类型、表达式 类型转换
未找到与约束ContractName Microsoft.VisualStudio.Text.ITextDocumentFactoryService...匹配的导出
QtDBus编程详解(二)
精通css(6)-图像背景那些事儿
错误解决:[A potentially dangerous Request.Form value was detected from the client]
企业如何实现持续集成与持续交付
《Java特种兵》1.3 简单数字游戏玩一玩