springboot 获取访问接口的请求的IP地址的实现
程序员文章站
2022-06-23 13:18:15
工具类:import javax.servlet.http.httpservletrequest;import java.net.inetaddress;import java.net.unknown...
工具类:
import javax.servlet.http.httpservletrequest; import java.net.inetaddress; import java.net.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(); } } // 对于通过多个代理的情况,第一个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; } }
方法调用:
(当接口 /test 被调用,request就能自动获取出来,然后调用工具类方法进行解析获取了。)
@requestmapping(value = "/test", method = requestmethod.get) public string test(httpservletrequest request){ //获取ip地址 string ipaddress =iputil.getipaddr(request); return ipaddress; }
到此这篇关于springboot 获取访问接口的请求的ip地址的实现的文章就介绍到这了,更多相关springboot 获取接口ip地址内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!