Java獲取登錄用戶的IP地址示例代碼
更新時間:2023年05月10日 09:38:50 作者:一個天蝎座的程序猿
在開發(fā)中我們經(jīng)常需要獲取用戶IP地址,通過地址來實現(xiàn)一些功能,下面這篇文章主要給大家介紹了關(guān)于Java獲取登錄用戶的IP地址的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
示例代碼如下
package com.audaque.util;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
public class GetIp {
public String getIpAddr(HttpServletRequest request){
String 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") || ipAddress.equals("0:0:0:0:0: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(","));
}
}
return ipAddress;
}
}
請求地址:
public class HttpContextUtil {
private HttpContextUtil(){
}
//獲取HttpServletRequest請求
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
}
}調(diào)用
sysLog.setOperationTime(LocalDateTimeUtil.getCurrentDatetime());
//獲取用戶名
sysLog.setUsername(UserUtil.get("username", String.class));
//獲取用戶ip地址
HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
sysLog.setIp(IPUtil.getIpAddr(request));總結(jié)
到此這篇關(guān)于Java獲取登錄用戶的IP地址的文章就介紹到這了,更多相關(guān)Java獲取登錄用戶IP地址內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java 中Comparable與Comparator詳解與比較
這篇文章主要介紹了java 中Comparable與Comparator詳解與比較的相關(guān)資料,需要的朋友可以參考下2017-04-04
springboot整合sentinel接口熔斷的實現(xiàn)示例
為了防止慢接口導致的服務(wù)阻塞,可以通過添加熔斷處理來避免應(yīng)用的大量工作線程陷入阻塞,保證其他接口的正常運行,本文介紹了如何使用Spring Boot與Sentinel進行接口熔斷的配置與實現(xiàn),感興趣的可以了解一下2024-09-09
Java?I/O?(Input/Output)文件字節(jié)流舉例詳解
Java的輸入輸出流(IO)是用于與外部設(shè)備(如文件、網(wǎng)絡(luò)連接等)進行數(shù)據(jù)交互的機制,下面這篇文章主要給大家介紹了關(guān)于Java?I/O?(Input/Output)文件字節(jié)流的相關(guān)資料,需要的朋友可以參考下2024-08-08
用StopWatch優(yōu)雅替代currentTimeMillis計算程序執(zhí)行耗時
別再用System.currentTimeMillis()計算程序執(zhí)行耗時了,擁抱StopWatch優(yōu)雅來優(yōu)雅的計算,代碼更簡潔效率更高,本文帶你了解StopWatch的使用2021-09-09
Mybatis-Plus根據(jù)自定義注解實現(xiàn)自動加解密的示例代碼
我們把數(shù)據(jù)存到數(shù)據(jù)庫的時候,有些敏感字段是需要加密的,從數(shù)據(jù)庫查出來再進行解密,如果我們使用的是Mybatis框架,那就跟著一起探索下如何使用框架的攔截器功能實現(xiàn)自動加解密吧,需要的朋友可以參考下2024-06-06

