处理java获取ip为0:0:0:0:0:0:0:1的问题

:0:0:0:0:0:0:1是ipv6的表现形式,对应ipv4来说相当于127.0.0.1,也就是本机

如果项目部署在本机win7/10系统,访问时是通过 localhost 来访问,

用java获取ip地址可能会出现该问题,这时获取的ip将是 0:0:0:0:0:0:0:1

要是机器在局域网中,访问时使用自己的ip访问,如 我的ip是 :192.168.123.126

访问url:http://192.168.123.126:8080/test

这时候请求会经过路由器转发,所以服务器获取的就是本机的局域网内ip,在java中获取的ip就是 192.168.123.126了

public static String getIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (!checkIP(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (!checkIP(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (!checkIP(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    private static boolean checkIP(String ip) {
        if (ip == null || ip.length() == 0 || "unkown".equalsIgnoreCase(ip)
                || ip.split(".").length != 4) {
            return false;
        }
        return true;
    }

或者

 //获取ip
    public static String getIpAddress() {
        HttpServletRequest request = getHttpServletRequest();
        String ip = request.getHeader("X-Forwarded-For");
        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 (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.getRemoteAddr();
            }
        }else if (ip != null && 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;
    }

注意
我发现这种情况只有在服务器和客户端都在同一台电脑上才会出现(例如用localhost访问的时候才会出现),后来上网查了查原因,原来是/etc/hosts这个东西作怪(在windows上应该是C:\Windows\System32\drivers\etc\hosts这个文件),仅仅只需要文件中的 # ::1 localhost 这一行被注释掉即可解决问题。另外localhost这个文件很有用,这里你可以添加自己的条目,例如添加 192.168.0.212 myweb 这样子,在浏览器中原来只能使用192.168.0.212来访问的,并可以使用myweb来进行替换。
如果还不能解决,本机访问的时候用127.0.0.1或本机ip代替localhost即可解决

你可能感兴趣的:(项目遇到的问题,局域网)