开发者

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

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;
	}

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

发现全部是127.0.0.1

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

public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = null;
		try {
			ipAddress = request.getHeader("x-forjavascriptwarded-for");
			if (ipAddress == null || ipAddress.length() == 0 || "un编程客栈known".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,多个IjavascriptP按照','分割
			if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".lengtwww.devze.comh()
				// = 15
				if (ipAddress.indexOf(",") > 0) {
					ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
				}
			}
		} catch (Exception e) {
			ipAddress = "";
		}
		return ipAddress;
	}

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

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

HttpServletRequest request = ((ServletRequestAttributes) (Requhttp://www.devze.comestContextHolder.currentRequestAttributes())).getRequest();
System.out.println("ip:"+IpUtil.getIpAddr(request));

这样就有ip地址了。

到此这篇关于springboot获取访问的ip地址的实现步骤的文章就介绍到这了,更多相关springboot获取访问ip地址内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜