springboot 获取访问接口的请求的IP地址的实现

网友投稿 895 2022-12-24

springboot 获取访问接口的请求的IP地址的实现

springboot 获取访问接口的请求的IP地址的实现

工具类:

import javax.servlet.http.HttpServletRequest;

import java-.InetAddress;

import java-.UnknownHostException;

/**

* @Author : JCccc

* @CreateTime : 2018-11-23

* @Description :

* @Point: Keep a good mood

**/

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();

}

}http://

// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割

if (ipAddress != null && ipAddress.length() > 15)http:// { // "***.***.***.***".length()

// = 15

if (ipAddress.indexOf(",") > 0) {

ipAddress = ipAddrehttp://ss.substring(0, ipAddress.indexOf(","));

}

}

} catch (Exception e) {

ipAddress="";

}

// ipAddress = this.getRequest().getRemoteAddr();

return ipAddress;

}

}

方法调用:

(当接口 /test 被调用,request就能自动获取出来,然后调用工具类方法进行解析获取了。)

@RequestMapping(value = "/test", method = RequestMethod.GET)

public String test(HttpServletRequest request){

//获取IP地址

String ipAddress =IpUtil.getIpAddr(request);

return ipAddress;

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:智能车载终端系统排行(智能车载终端是什么)
下一篇:flutter 并发请求(flutter网络请求)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~