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

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

新建springboot工程

 

 选择spring web

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

启动工程:

控制台输出日志: 

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

浏览器返回如图

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

查看本机ip

 

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

返回如下页面

开启nginx转发:编辑nginx.conf

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

 双击启动nginx

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

 

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

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值