当前位置:   article > 正文

springboot获取客户端IP及IP归属地_springboot获取ip地址

springboot获取ip地址

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

新建springboot工程

 

 选择spring web

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

  1. package com.example.demo.utils;
  2. import javax.servlet.http.HttpServletRequest;
  3. public class IpUtil {
  4. static final String UNKNOWN = "unknown";
  5. public static String getIpAddr(HttpServletRequest request) {
  6. if (request == null) {
  7. return UNKNOWN;
  8. }
  9. String ip = request.getHeader("x-forwarded-for");
  10. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  11. ip = request.getHeader("Proxy-Client-IP");
  12. }
  13. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  14. ip = request.getHeader("X-Forwarded-For");
  15. }
  16. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  17. ip = request.getHeader("WL-Proxy-Client-IP");
  18. }
  19. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  20. ip = request.getHeader("X-Real-IP");
  21. }
  22. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  23. ip = request.getRemoteAddr();
  24. }
  25. System.out.println(ip);
  26. return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
  27. }
  28. }

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

  1. package com.example.demo.web;
  2. import com.example.demo.utils.IpUtil;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import javax.servlet.http.HttpServletRequest;
  6. @RestController
  7. public class TestController {
  8. @RequestMapping(value = "")
  9. String getIp(HttpServletRequest request){
  10. return IpUtil.getIpAddr(request);
  11. }
  12. }

启动工程:

控制台输出日志: 

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

浏览器返回如图

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

查看本机ip

 

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

返回如下页面

开启nginx转发:编辑nginx.conf

  1. location / {
  2. root html;
  3. #转发
  4. proxy_pass http://127.0.0.1:8080/;
  5. index index.html index.htm;
  6. }

 双击启动nginx

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

 

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

  1. location / {
  2. root html;
  3. proxy_set_header Host $http_host;
  4. proxy_set_header X-Real-IP $remote_addr;
  5. proxy_set_header REMOTE-HOST $remote_addr;
  6. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  7. proxy_pass http://127.0.0.1:8080/;
  8. index index.html index.htm;
  9. }

重启nginx

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/405730
推荐阅读
相关标签
  

闽ICP备14008679号