springboot 獲取訪問接口的請求的IP地址的實現(xiàn)
更新時間:2021年07月27日 15:56:59 作者:小目標青年
本文主要介紹了springboot獲取訪問接口的請求的IP地址的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
工具類:
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")) { // 根據(jù)網(wǎng)卡取本機配置的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地址的實現(xiàn)的文章就介紹到這了,更多相關springboot 獲取接口IP地址內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java使用Jsoup解析html網(wǎng)頁的實現(xiàn)步驟
Jsoup是一個用于解析HTML文檔的Java庫,本文主要介紹了Java使用Jsoup解析html網(wǎng)頁的實現(xiàn)步驟,可以提取文本、鏈接、圖片等,具有一定的參考價值,感興趣的可以了解一下2024-02-02Spring的@Value注入復雜類型(通過@value注入自定義類型)
Spring的@Value可以注入復雜類型嗎?今天教你通過@value注入自定義類型。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12Springboot?接口需要接收參數(shù)類型是數(shù)組問題
這篇文章主要介紹了Springboot?接口需要接收參數(shù)類型是數(shù)組問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01SpringMVC使用hibernate-validator進行參數(shù)校驗最佳實踐記錄
這篇文章主要介紹了SpringMVC使用hibernate-validator進行參數(shù)校驗最佳實踐,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-05-05idea新建Springboot項目,設置默認maven和jdk版本方式
這篇文章主要介紹了idea新建Springboot項目,設置默認maven和jdk版本方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12