公告:欢迎访问,查看更多资源请点我^.^!            点我关闭广告
Java工具~获取客户端IP信息
2018-06-05 09:54:35
693人阅读
评论(0)
分类:Java
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
* @author 赵超
* @e-mail 18701321850@163.com
* @description 常用获取客户端信息的工具
* @createTime 2017/6/24 - 16:36.
*/

public final class NetworkUtil {
/**
* Logger for this class
*/
private static Logger logger = Logger.getLogger(NetworkUtil.class);

/**
* 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址;
*
* @param request
* @return
* @throws IOException
*/
public final static String getIpAddress(HttpServletRequest request) throws IOException {
// 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址

String ip = request.getHeader("X-Forwarded-For");
// if (logger.isInfoEnabled()) {
// logger.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip);
// }

if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
// if (logger.isInfoEnabled()) {
// logger.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip);
// }
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
// if (logger.isInfoEnabled()) {
// logger.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip);
// }
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
// if (logger.isInfoEnabled()) {
// logger.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip);
// }
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
// if (logger.isInfoEnabled()) {
// logger.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip);
// }
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
// if (logger.isInfoEnabled()) {
// logger.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip);
// }
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
for (int index = 0; index < ips.length; index++) {
String strIp = (String) ips[index];
if (!("unknown".equalsIgnoreCase(strIp))) {
ip = strIp;
break;
}
}
}
return ip;
}
}


分享一下:
赞一下(0)
博主资料
博主头像
zc521106
文章:34
浏览:19899
文章分类
Java(12)
NoSql(112)
数据库(12)
前端(12)
阅读排行
Java基础知识
(12)
NoSql应用
(112)
数据库Oracle语法
(12)
前端常用工具类
(12)
java web项目
(12)
linux安装mysql
(12)
评论区
这篇文章怎么样?写点评论吧!
姓名:
邮箱:
有回复时通知我:
发表
回复【10.20.30.32】:
暂无评论,快抢沙发!
* 以上用户言论只代表其个人观点,不代表iBlog网站的观点或立场,如有任何疑问请随时联系管理员...