码上敲享录 > java入门知识分享 > java如何获取访问真实IP地址

java如何获取访问真实IP地址

上一章章节目录下一章 2018-07-23已有4786人阅读 评论(0)

java如何获取访问真实IP地址?


解决方法:

获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址,如果没有代理,则获取真实ip

public static String getIp(HttpServletRequest request){

//代理进来,则透过防火墙获取真实IP地址

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.getHeader("X-Real-IP");

   }


//如果没有代理,则获取真实ip

if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

ip = request.getRemoteAddr();

}


return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;

}


本文地址:http://yayihouse.com/yayishuwu/chapter/1339


3

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交