Tomcat运行时获取IP及端口号

直接上代码

        public String getIP(){
        String ip =null;
        InetAddress address;
        try {
            address = InetAddress.getLocalHost();
            ip = address.getHostAddress();
        } catch (Exception e) {
        }
        return ip;
    }
    public String getPort() throws Exception{
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        Set objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        String port = objectNames.iterator().next().getKeyProperty("port");
        return port;
    }

public string getMAC(){
InetAddress address = InetAddress.getLocalHost();
byte[] mac =NetworkInterface.getByInetAddress(address).getHardwareAddress();
StringBuffer sb=new StringBuffer();
for(int i=0;i

注意:当获取端口号时,一定得是在容器中运行时才能获取,因为获取端口号是通过查找容器自身的MBean来获取的,离开容器就获取不到对应的MBean,会报空指针异常,同时此思路还能获取容器中所有的应用名、sevlet名等容器运行信息

你可能感兴趣的:(Tomcat运行时获取IP及端口号)