Get the server port number from tomcat without a request

前端 未结 12 1599
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 06:32

Is there any Tomcat API or configuration available which can tell an application (probably on startup), what port its running on without a request?

Imagine a scenari

12条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 07:06

    With this:

    List getEndPoints() throws MalformedObjectNameException,
            NullPointerException, UnknownHostException, AttributeNotFoundException,
            InstanceNotFoundException, MBeanException, ReflectionException {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        QueryExp subQuery1 = Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"));
        QueryExp subQuery2 = Query.anySubString(Query.attr("protocol"), Query.value("Http11"));
        QueryExp query = Query.or(subQuery1, subQuery2);
        Set objs = mbs.queryNames(new ObjectName("*:type=Connector,*"), query);
        String hostname = InetAddress.getLocalHost().getHostName();
        InetAddress[] addresses = InetAddress.getAllByName(hostname);
        ArrayList endPoints = new ArrayList();
        for (Iterator i = objs.iterator(); i.hasNext();) {
            ObjectName obj = i.next();
            String scheme = mbs.getAttribute(obj, "scheme").toString();
            String port = obj.getKeyProperty("port");
            for (InetAddress addr : addresses) {
                if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || 
                    addr.isMulticastAddress()) {
                    continue;
                }
                String host = addr.getHostAddress();
                String ep = scheme + "://" + host + ":" + port;
                endPoints.add(ep);
            }
        }
        return endPoints;
    }
    

    You will get a List like this:

    [http://192.168.1.22:8080]
    

提交回复
热议问题