服务器ip目前还没找到方法,此方法InetAddress.getLocalHost().getHostAddress()获取的是IP地址为127.0.0.1,在linux服务器上,在本地运行tomcat的话,则获取的是连接的网络IP地址。
进入正题,端口的获取方法,应为写的是定时任务,所以并没有request的请求,这时,我们则要借助jmx来实现了,代码如下:
//通过mBeanServer获得端口号
MBeanServer mBeanServer = null;
ArrayListmBeanServers = MBeanServerFactory.findMBeanServer(null);
if (mBeanServers.size() > 0) {
for (MBeanServer _mBeanServer : mBeanServers) {
mBeanServer = _mBeanServer;
break;
}
}
if (mBeanServer == null) {
throw new IllegalStateException("没有发现JVM中关联的MBeanServer.");
}
SetobjectNames = null;
try {
objectNames = mBeanServer.queryNames(new ObjectName("Catalina:type=Connector,*"), null);
} catch (MalformedObjectNameException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
if (objectNames == null || objectNames.size() <= 0) {
throw new IllegalStateException("没有发现JVM中关联的MBeanServer : "
+ mBeanServer.getDefaultDomain() + " 中的对象名称.");
}
try {
for (ObjectName objectName : objectNames) {
String protocol = (String) mBeanServer.getAttribute(objectName, "protocol");
if (protocol.equals("HTTP/1.1")) {
int port = (Integer) mBeanServer.getAttribute(objectName, "port");
}
// String scheme = (String) mBeanServer.getAttribute(objectName,
// "scheme");
// int port = (Integer) mBeanServer.getAttribute(objectName,
// "port");
}
} catch (AttributeNotFoundException e) {
e.printStackTrace();
} catch (InstanceNotFoundException e) {
e.printStackTrace();
} catch (MBeanException e) {
e.printStackTrace();
} catch (ReflectionException e) {
e.printStackTrace();
}
在此记录一下,以后也方便找啦