The problem that java obtains ip as 0:0:0:0:0:0:0:1 [transfer]

0:0:0:0:0:0:0:1 is the representation of ipv6, which is equivalent to 127.0.0.1 for ipv4, which is the local machine.

If project is deployed in the local win7 system, the access is through localhost. Access,

using java to obtain the ip address may cause this problem, then the obtained ip will be 0:0:0:0:0:0:0:1



If the machine is in the local area network, use its own ip to access, such as My ip is: 192.168.123.156

Access url: http://192.168.123.156:8080/test

At this time, the request will be forwarded by the router, so the server obtains the local ip of the local area network, and the ip obtained in java is 192.168 .123.156 up

    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;
    }




The reason why the value obtained by request.getRemoteAddr() is 0:0:0:0:0:0:0:1 and the solution ) The value obtained is 0:0:0:0:0:0:0:1. Why is this? Logically speaking, it should be 127.0.0.1. Why does the obtained value become ipv6? And I found that this situation only occurs when the server and the client are on the same computer (for example, when accessing with localhost). Later, I checked the reason on the Internet, and it turned out that /etc/hosts was the culprit ( On windows, it should be the file C:\Windows\System32\drivers\etc\hosts), just comment out the line # ::1 localhost in the file to solve the problem. In addition, the localhost file is very useful, where you can add your own entries, such as adding 192.168.0.212 myweb, which can only be accessed by 192.168.0.212 in the browser, and can be replaced by myweb.

If it still can't be solved, use 127.0.0.1 or the local ip instead of localhost to solve the problem.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326119202&siteId=291194637