• 【Java】Spring Boot获取请求接口的客户端IP


        private String getIpAddress(HttpServletRequest request) {
            String ip = request.getHeader("x-forwarded-for");
            if (ip == null || ip.length() == 0 || "unknow".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.getRemoteAddr();
                if (ip.equals("127.0.0.1")) {
                    //根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    ip = inet.getHostAddress();
                }
            }
            // 多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
            if (ip != null && ip.length() > 15) {
                if (ip.indexOf(",") > 0) {
                    ip = ip.substring(0, ip.indexOf(","));
                }
            }
            return ip;
        }

    备注:在windows7 使用localshot访问时,获取到的IP地址为0:0:0:0:0:1 原因是localhost解析不出来 需要使用正常的IP地址访问时,则可正确的得到访问client端的IP地址

  • 相关阅读:
    BestCoder 2nd Anniversary/HDU 5718 高精度 模拟
    FZU 2168 前缀和+dp递推
    poj 1088 记忆化搜索
    Codeforces Round #241 (Div. 2) B dp
    poj 3053 优先队列处理
    取消修改
    csv乱码
    iconv()
    cakephp中sql查询between
    虚拟机上linux与windows之间复制粘贴
  • 原文地址:https://www.cnblogs.com/danhuai/p/16359641.html
Copyright © 2020-2023  润新知