1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > springboot获取客户端IP及IP归属地

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

时间:2019-10-16 03:44:30

相关推荐

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;@RestControllerpublic 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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。