How does Java get the real IP address of the client host

During the project development, I encountered a need to bind the system project to the IP address of a certain host, so that the system can only be used on a certain host. Don’t ask me why, this is the first time I have encountered Seeing such a strange demand, of course, don’t ask me why I don’t use permission control. The current permission control component has developed better. The answer is that the leader thinks it’s troublesome, and it’s difficult for me. Solve, how to solve this matter? My initial thought was this

First, see if you can use Jquery on the front-end page to obtain the IP address of the client, but unfortunately, the editor has tried various methods, but there is no way to solve it. After wandering on the Internet for a long time, the obtained information either cannot run, or It is 127.0.0.1 obtained, and the editor is also very helpless, so the idea of ​​​​getting the ip address by the Jquery front end is abandoned by reality

Next, the editor changed his thinking. Now that the background development is very mature, let’s see if we can try to use the Java code related to the back end to achieve the goal of obtaining the IP address of the client host. For this piece of knowledge, in fact, related information on the Internet The content is also relatively small, but the hard work pays off, and the result of wandering around finally has the result. Let the editor find a method to obtain the real IP address on the Internet, and the code is as follows:

public Result  getHostIp(HttpServletRequest request){
        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();
        }

        if (ip!=null&&!"".equals(ip)){
            return new Result(true,"查询ip成功",ip);
        }else{
            return new Result(false,"查询ip失败");
        }

    }

That's right, the above string of codes, the editor provides a method, you can run this string of codes in a class, but I also encountered the returned 0:0 in the process of using: 0:0:0:0:0:1, why? Because the editor used the same computer as the project server when visiting this page, so what I got is this

When the editor uses other hosts to access the website, the correct IP address is obtained, and the goal is achieved

 

 

Guess you like

Origin blog.csdn.net/weixin_50249953/article/details/128616947