用request获取请求地址Ip
生活随笔
收集整理的這篇文章主要介紹了
用request获取请求地址Ip
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java獲取請求地址Ip
public String getIpAddr(HttpServletRequest request) throws Exception {String ipAddress = null;String[] header = {"x-forwarded-for","Proxy-Client-IP","WL-Proxy-Client-IP"};for (int i = 0; i < header.length; i++) {ipAddress = request.getHeader(header[i]);if (StringUtils.isEmpty(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {continue;} else {break;}}if (StringUtils.isEmpty(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getRemoteAddr();if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {// 根據網卡取本機配置的IPInetAddress inet = null;try {inet = InetAddress.getLocalHost();} catch (UnknownHostException e) {e.printStackTrace();}ipAddress = inet.getHostAddress();}}// 對于通過多個代理的情況,第一個IP為客戶端真實IP,多個IP按照','分割// "***.***.***.***".length() = 15if (!StringUtils.isEmpty(ipAddress) && ipAddress.length() > 15) {if (ipAddress.indexOf(",") > 0) {ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));}} else if (StringUtils.isEmpty(ipAddress)) {throw new Exception("獲取ip異常");}return ipAddress; }總結
以上是生活随笔為你收集整理的用request获取请求地址Ip的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 组合数学$1排列组合
- 下一篇: STM32CUBE+自平衡车实践篇3.4