SpringBoot 获取当前登录用户IP
2024-08-26 18:04:11
控制器方法:
@RequestMapping(value = "/getIp", method = RequestMethod.POST)
@ResponseBody
public String getIp(HttpServletRequest request) {
return IpUtil.getIpAddr(request);
}
工具类方法:
public class IpUtil {
public static String getIpAddr(HttpServletRequest request) {
String ipAddress = null;
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
ipAddress="";
}
// ipAddress = this.getRequest().getRemoteAddr(); return ipAddress;
}
}
最新文章
- github 相关英语
- 安卓中級教程(9):pathbutton中的animation.java研究(2)
- 【摘】BPMN2.0-概要
- 引入Ember插件 大概流程
- unity3d插件Daikon Forge GUI 中文教程4-高级控件Checkbox和dropdownlis的使用
- javascript笔记8-表单脚本、JSON、AJAX
- Codeforces Round #185 (Div. 2) B. Archer 水题
- js限制文本框输入字数
- 九、 合成(Composite)模式 --结构模式(Structural Pattern)
- 查询ID为5的数据的前后各一行数据,ID不连续
- FFmpeg 协议初步学习
- Makefile.am编写规则
- js中的全局函数
- Java面试步步走
- Python:名片管理系统(增加登录功能后出现问题,求教)
- I/O多路转接模型
- 一、Subversion服务
- 用Verilog语言实现一个简单的MII模块
- [leetcode]236. Lowest Common Ancestor of a Binary Tree二叉树最近公共祖先
- 20155208 实验四 Android开发基础
热门文章
- 德卡Z90读卡器读取社保卡,德卡Z90读卡器CSharp示例程序源码
- 【深入Struts2】获取ServletAPI的三种方式
- 001 SpringMVC的helloWorld程序
- 2013-2014 ACM-ICPC Brazil Subregional Programming Contest 题解
- tomcat配置问题:访问http://localhost:8080/ 遇到 Access Error: 404
- mobile开发备忘
- Failed to connect socket to '/var/run/libvirt/libvirt-sock'的问题解决
- ARM汇编编程基础之一 —— 寄存器
- C#快速找出磁盘内的所有文件
- USB with NXP Microcontrollers