代码之家  ›  专栏  ›  技术社区  ›  anuni

如何在WebFrIP中获取客户端IP?

  •  2
  • anuni  · 技术社区  · 8 年前

    我曾经调用httpservletrequest.getremoteaddr()来获取客户端IP。

    我想知道怎样才能通过服务器网络交换获得它。

    我最好的猜测是:

      serverWebExchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
    

    对吗?

    谢谢

    里昂

    2 回复  |  直到 8 年前
        1
  •  1
  •   Brian Clozel    8 年前

    是的,这是实现这一目标的正确方法。 注意,如果您希望支持forwarded或x-forwarded-*http请求头,则需要在服务器配置级别对其进行配置。

        2
  •  0
  •   Cherry    7 年前

    您还可以添加 org.springframework.http.server.ServerHttpRequest 作为参数 @RerquestMapping 注释方法并从中获取IP地址:

    @GetMapping("/myPath")
    public void someMethod(ServerHttpRequest request) {
        System.out.println(request.getRemoteAddress().getAddress().getHostAddress();)
    }