springboot 獲取訪問(wèn)接口的請(qǐng)求的IP地址的實(shí)現(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)卡取本機(jī)配置的IP InetAddress inet = null; try {inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) {e.printStackTrace(); } ipAddress = inet.getHostAddress();} } // 對(duì)于通過(guò)多個(gè)代理的情況,第一個(gè)IP為客戶端真實(shí)IP,多個(gè)IP按照’,’分割 if (ipAddress != null && ipAddress.length() > 15) { // '***.***.***.***'.length()// = 15if (ipAddress.indexOf(',') > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(','));} }} catch (Exception e) { ipAddress='';}// ipAddress = this.getRequest().getRemoteAddr(); return ipAddress; }}
方法調(diào)用:
(當(dāng)接口 /test 被調(diào)用,request就能自動(dòng)獲取出來(lái),然后調(diào)用工具類方法進(jìn)行解析獲取了。)
@RequestMapping(value = '/test', method = RequestMethod.GET)public String test(HttpServletRequest request){ //獲取IP地址 String ipAddress =IpUtil.getIpAddr(request); return ipAddress;}
到此這篇關(guān)于springboot 獲取訪問(wèn)接口的請(qǐng)求的IP地址的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)springboot 獲取接口IP地址內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. js實(shí)現(xiàn)跳一跳小游戲2. IDEA中用maven連接數(shù)據(jù)庫(kù)的教程3. JVM之class文件結(jié)構(gòu)4. js實(shí)現(xiàn)貪吃蛇小游戲(加墻)5. Python中Anaconda3 安裝gdal庫(kù)的方法6. asp.net core 認(rèn)證和授權(quán)實(shí)例詳解7. Python進(jìn)行統(tǒng)計(jì)建模8. python對(duì)批量WAV音頻進(jìn)行等長(zhǎng)分割的方法實(shí)現(xiàn)9. Ajax報(bào)錯(cuò)400的參考解決辦法10. CSS linear-gradient屬性案例詳解
