springboot获取客户端IP及IP归属地

思路:1.reqest对象获取客户端IP,2.第三方接口获取IP属地

新建springboot工程

springboot获取客户端IP及IP归属地_第1张图片

springboot获取客户端IP及IP归属地_第2张图片 

 选择spring web

springboot获取客户端IP及IP归属地_第3张图片

在com.example.demo包下新建utils工具类包,并新建IpUtil工具类代码如下:

package com.example.demo.utils;

import javax.servlet.http.HttpServletRequest;

public class IpUtil {
    static final String UNKNOWN = "unknown";

    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return UNKNOWN;
        }
        String ip = request.getHeader("x-forwarded-for");
        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("X-Forwarded-For");
        }
        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("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        System.out.println(ip);
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

}

 在com.example.demo包下新建utils工具类包,并新建TestController类代码如下:

package com.example.demo.web;


import com.example.demo.utils.IpUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
@RestController
public class TestController {
    @RequestMapping(value = "")
    String getIp(HttpServletRequest request){

        return IpUtil.getIpAddr(request);
    }
}

启动工程:

springboot获取客户端IP及IP归属地_第4张图片

控制台输出日志:springboot获取客户端IP及IP归属地_第5张图片 

浏览器访问http://localhost:8080 

浏览器返回如图springboot获取客户端IP及IP归属地_第6张图片

 查看本机局域网地址并确定手机或其他设备与本机在同一局域网命令行输入ipconfig

查看本机ip

springboot获取客户端IP及IP归属地_第7张图片

 

用手机访问http://192.168.1.210:8080

返回如下页面

springboot获取客户端IP及IP归属地_第8张图片

开启nginx转发:编辑nginx.conf

location / {
            root    html;
#转发
		    proxy_pass   http://127.0.0.1:8080/;
           index  index.html index.htm;
        }

 双击启动nginx

springboot获取客户端IP及IP归属地_第9张图片

用手机访问http://192.168.1.210返回127.0.0.1

 springboot获取客户端IP及IP归属地_第10张图片

ip地址错误: 解决方法-更改nginx.conf

location / {
            root    html;
			 proxy_set_header Host $http_host;
             proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header REMOTE-HOST $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		    proxy_pass   http://127.0.0.1:8080/;
           index  index.html index.htm;
        }

重启nginx

你可能感兴趣的:(tcp/ip,网络协议,网络)