• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

yxchun

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

SpringBoot 项目获取客户端IP地址

 

package tr.demo;


import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GetIPService {

//方式一 @GetMapping(
"/getIp") public String getIP(HttpServletRequest request){ String remoteAddr = request.getRemoteAddr(); String remoteHost = request.getRemoteHost(); System.out.println("remoteAddr="+remoteAddr); System.out.println("remoteHost="+remoteHost); return remoteAddr; }
//方式二 @GetMapping(
"getIp002") public String getIpAddress(HttpServletRequest request) { String ipAddress = request.getHeader("X-Forwarded-For"); if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); } System.out.println("ipAddress="+ipAddress); return ipAddress.split(",")[0]; } }

 

posted on 2024-11-19 09:52  yxchun  阅读(788)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3