javaweb项目通过F5负载,获取客户端真实ip
生活随笔
收集整理的這篇文章主要介紹了
javaweb项目通过F5负载,获取客户端真实ip
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
場景:
? ? ? ?在演練環境中,通過F5做負載均衡,前端項目獲取的卻是F5機器的ip。
日志截圖:
分析:
? ? ? ?從上圖可以看到,X-Forwarded-For是null,其他的也都是null,只有通過getRemoteAddr()可以獲取ip,但不是我們想要的;
那么問題就來了,X-Forwarded-For為什么是null?
解決:
? ? ? ?經與負責F5的技術人員溝通是其沒有在F5中添加X-Forwarded-For,導致它為null,之后添加上后,再獲取時,就可以獲取到客戶端真實的ip了;
如圖:
F5配置
F5中開啟AutoMap,并傳遞X-Forwarded-For值
開啟F5源地址轉換"Auto Map"
https://images2015.cnblogs.com/blog/582266/201605/582266-20160517125509888-1957873778.png
方式一: 在http profile中開啟X-Forwarded-For
方式二:在iRule中開啟X-Forwarded-For
when HTTP_REQUEST {HTTP::header insert "X-Forwarded-For" [IP::client_addr] }具體參考官方文檔: 傳送門
java項目獲取
public String getIpAddress(HttpServletRequest request) {// 獲取請求主機IP地址,如果通過代理進來,則透過防火墻獲取真實IP地址String ip = request.getHeader("X-Forwarded-For");String ipx = request.getHeader("x-forwarded-for");logger.info("------ X-Forwarded-For ip:" + ip);logger.info("------ x-forwarded-for ip:" + ipx);if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {// 多次反向代理后會有多個ip值,第一個ip才是真實ipif (ip.indexOf(",") != -1) {ip = ip.split(",")[0];logger.info("------ 第一個 ip:" + ip);}}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("Proxy-Client-IP");logger.info("------ Proxy-Client-IP ip:" + ip);}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("WL-Proxy-Client-IP");logger.info("------ WL-Proxy-Client-IP ip:" + ip);}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_CLIENT_IP");logger.info("------ HTTP_CLIENT_IP ip:" + ip);}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_X_FORWARDED_FOR");logger.info("------ HTTP_X_FORWARDED_FOR ip:" + ip);}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("X-Real-IP");logger.info("------ X-Real-IP ip:" + ip);}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getRemoteAddr();logger.info("------ getRemoteAddr ip:" + ip);}logger.info("客戶端訪問ip地址為:【" + ip + "】");return ip;}author:su1573
鄙人記錄生活點滴,學習并分享,請多指教!!!
如需交流,請聯系 sph1573@163.com,鄙人看到會及時回復
總結
以上是生活随笔為你收集整理的javaweb项目通过F5负载,获取客户端真实ip的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java.lang.NoSuchMeth
- 下一篇: 三、spring boot 1.5.4