简体   繁体   English

如何在Java tomcat服务器中获取主机地址

[英]How to get host adress in java tomcat server

I'm trying to get IP address from DNS like this: 我试图像这样从DNS获取IP地址:

InetAddress hostAddr = InetAddress.getByName("somentp.server.com");

but hostAddr is null, it seems like it can't find it. 但是hostAddr为null,似乎找不到它。 I'm doing this from a thread in Java, which is executed on a ServletContextListener in Tomcat Server. 我是从Java中的一个线程执行此操作的,该线程在Tomcat服务器中的ServletContextListener上执行。 If i do this from the same thread but in a normal Java app, it works perfectly fine. 如果我从同一线程但在普通的Java应用程序中执行此操作,则效果很好。 The goal of all this is to use the address as argument to NTP Client API . 所有这一切的目的是将地址用作NTP Client API的参数。

I don't know if it's a problem of Tomcat, some configuration or any other bug 我不知道这是Tomcat的问题,某些配置还是任何其他错误

I hope you can help me, thanks 我希望你能帮助我,谢谢

As per the inetAddress#getByName docs , the static method getByName doesn't return a null unless the method throws one of the two exceptions UnknownHostException or SecurityException . 根据inetAddress#getByName 文档 ,静态方法getByName不会返回null,除非该方法引发两个异常UnknownHostExceptionSecurityException

Your code in the ServletContextListener seems to be swallowing the exception. 您在ServletContextListener代码似乎吞没了该异常。 You need to debug that code and find out which exception out of the above two is being thrown by the call to getByName. 您需要调试该代码,并找出对getByName的调用引发了以上两个异常中的哪个异常。 Once you determine the exception type, you can take an appropriate action to correct the error reported by that exception. 确定异常类型后,您可以采取适当的措施来纠正该异常报告的错误。 Eg if the exception is UnknownHostException , you might want to check the host name argument that you are passing to the method. 例如,如果异常是UnknownHostException ,则可能要检查传递给该方法的主机名参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM