当前位置: 代码网 > it编程>编程语言>Java > springboot获取访问的ip地址的实现步骤

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

2025年10月24日 Java 我要评论
1、用shiro的方式获取到的是127.0.0.1,或者用request.getremoteaddr()也会是127.0.0.1(这个与浏览器地址有关)httpservletrequest reque

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)

相关文章:

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

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com