首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Tomcat上识别服务器(HttpServletRequest.getLocalAddr()失败)

在Tomcat上识别服务器(HttpServletRequest.getLocalAddr()失败)
EN

Stack Overflow用户
提问于 2013-02-09 03:48:05
回答 3查看 1.3K关注 0票数 1

使用Apache背后的Tomcat设置,如何轻松确定服务器的id (理想情况下是IP地址)?

具体情况是,在负载均衡器后面设置了多个服务器,因此传入的请求主机名不是唯一的,不足以识别用于日志记录的特定服务器。不幸的是,使用HttpServletRequest.getLocalAddr()返回的是相同的主机名,而不是预期的IP地址(我假设这与这个非常老的问题有关:https://issues.apache.org/bugzilla/show_bug.cgi?id=46082)。

是否有办法使getLocalAddr()按照文档所述执行,或者是否需要其他方法来查询服务器的IP地址?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-02-09 06:31:36

对于我的情况,解决方案是直接获取服务器的IP地址,而不是尝试通过HttpServleRequest获取本地地址。

我通过以下方式缓存IP,以便在我的过滤器中使用:

代码语言:javascript
复制
private static final String serverIp;
static {
    String addressString = null;
    try
    {
        InetAddress address = InetAddress.getLocalHost();
        addressString = address.getHostAddress();
    } catch (Exception e)
    {
        logger.error("Exception while attempting to determine local ip address",e);
    }

    if (addressString != null) serverIp = addressString;
    else serverIp = "unknown";
}
票数 1
EN

Stack Overflow用户

发布于 2013-02-09 03:52:20

在我们的项目中,我们使用JMX来获取所有配置信息。这需要几个步骤,因为它类似于向下导航到server.xml文件,该链接包含一些信息:http://oss.wxnet.org/mbeans.html

如果你想要的只是IP,这可能有点夸张,但我想我还是把它扔出去吧。

代码语言:javascript
复制
  MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
  Set<ObjectName> theConnectors = mbeanServer.queryNames(
      new ObjectName("Catalina:type=Connector,*"),
      null);
  if (theConnectors != null)
  {
      for (ObjectName nextConnectorName : theConnectors)
      {
        InetAddress theInetAddress = (InetAddress) mbeanServer.getAttribute(
          nextConnectorName,
          "address");
        if (theInetAddress != null)
        {
          ipAddress = theInetAddress.getHostAddress();
        }
        if (!StringUtil.isEmpty(ipAddress))
        {
          // found the IP address
          break;
        }
      }
  }
票数 2
EN

Stack Overflow用户

发布于 2019-08-30 18:36:57

我最近遇到了类似的问题(在最初的问题几年后),并找到了这个问题和答案。在我的例子中,问题是ServletRequest#getLocalAddr()实现返回的是远程地址,而不是本地地址。该问题是由Tomcat v9.0.22中的回归引起的。该问题已在v9.0.23中修复。请在此处查看问题和答案:

https://stackoverflow.com/a/57725039/9602527

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14780207

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档