it编程 > 编程语言 > Java

springboot获取访问的ip地址的实现步骤

4人参与 2025-10-24 Java

1、用shiro的方式获取到的是127.0.0.1,或者用request.getremoteaddr()也会是127.0.0.1(这个与浏览器地址有关)

httpservletrequest request;
request.getremoteaddr();

shiro

/**
	 * 获取ip
	 * 
	 * @return
	 */
	private string getip() {
		subject subject = securityutils.getsubject();
		string host = subject.getsession().gethost();
		return host;
	}

发现全部是127.0.0.1

2、网上有个兄弟写了一个方法,测试以后发现是可以获取到ip的,在本机上测试成功,地址栏上面输入ip:port的形式访问。

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")) {
					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 = "";
		}
		return ipaddress;
	}

不是在controller调用也是可以的,也就是没有httpservletrequest request参数情况下:

httpservletrequest request = ((servletrequestattributes) (requestcontextholder.currentrequestattributes())).getrequest();
system.out.println("ip:"+iputil.getipaddr(request));

这样就有ip地址了。

到此这篇关于springboot获取访问的ip地址的实现步骤的文章就介绍到这了,更多相关springboot获取访问ip地址内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

您想发表意见!!点此发布评论

推荐阅读

对SpringBoot项目配置文件进行加密实现过程

10-24

Java杨辉三角、洗牌算法详细示例代码

10-24

Java如何将文件格式为psd的文件转换为base64详解

10-24

Springboot配置文件加密方式

10-24

Springboot使用RabbitMq延迟队列和死信队列详解

10-24

Spring Security密码编辑器示例详解

10-24

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论