直接上代码
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<ObjectName> 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<mac.length;i++){
if(i!=0){sb.append("-");}
int temp = mac[i]&0xff;
String str = Integer.toHexString(temp);
if(str.length()==1){sb.append("0"+str);}else{
sb.append(str);
}
}
return sb.toString();
}
注意:当获取端口号时,一定得是在容器中运行时才能获取,因为获取端口号是通过查找容器自身的MBean来获取的,离开容器就获取不到对应的MBean,会报空指针异常,同时此思路还能获取容器中所有的应用名、sevlet名等容器运行信息
网友评论