zoukankan      html  css  js  c++  java
  • java 获取访问主机的ip地址

    Java的api的说法:

    getHeader

    public java.lang.String getHeader(java.lang.String name)

    Return the first value of the specified header, if any; otherwise, return null

    返回指定标头的第一个值(如果有的话);否则返回null。

    Specified by:

    getHeader in interface javax.servlet.http.HttpServletRequest

    javax.servlet.http.httpservletrequest getheader接口

    Parameters:

    name - Name of the requested header

    响应头文件中的json数据中的key

     

     

    下面代码是通过HttpServletRequest获取主机的ip地址:
    /**
         * 获取登陆IP
         * @param request
         * @param response
         * @return 
         */
        public String getIpAddr(HttpServletRequest request) {
    //处理代理访问获取不到真正的ip问题的        
    String ip = request.getHeader("x-forwarded-for");
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    //获取代理中中的ip
                ip = request.getHeader("PRoxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    //获取代理中中的ip
    
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    //非代理的情况获取ip
                ip = request.getRemoteAddr();
            }
            
            return ip;
        }

     遇到的问题,有时候我们获取的ip为0.0.0.0.0.1为ipv6的的地址,这是由于服务器和客户端在一起导致的,在服务器端的host文件中指定localhost的ip地址为127.0.0.1或是真实的ipv4的地址就可以。

  • 相关阅读:
    解决ubuntu中firefox浏览器总是提示找不到server的问题
    Android学习笔记(14):相对布局RelativeLayout
    浅析java(多方面解读)
    做自己
    SGU 261. Discrete Roots (N次剩余)
    hdu1115 Lifting the Stone(几何,求多边形重心模板题)
    Android编码规范
    hdu 3790 最短路径问题
    怎样在gluster的源代码中加入自己的xlator
    处理空列表
  • 原文地址:https://www.cnblogs.com/gynbk/p/7026245.html
Copyright © 2011-2022 走看看