赞
踩
思路:1.reqest对象获取客户端IP,2.第三方接口获取IP属地
选择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
用手机访问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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。