import lombok.extern.slf4j.Slf4j;
import javax.management.*;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;
/**
* @author :LiuShihao
* @date :Created in 2020/8/11 9:16 上午
* @desc :获得服务器IP地址和Tomcat端口号工具类
*/
@Slf4j
public class GetIPPortUtil {
/**
* 获取本机ip
* @return
*/
public static Set<String> getInetAddresses() {
Set<String> ipList = new HashSet<String>();
Enumeration allNetInterfaces = null;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
System.out.println(netInterface.getName());
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
log.info("本机的IP = " + ip.getHostAddress());
String ipTemp = ip.toString().replace("/", "");
ipList.add(ipTemp);
}
}
}
log.info("本机iplist数量为" + ipList.size());
return ipList;
}
/**
* 获取当前Tomcat实例的端口
*
* @return
*/
public static String getPortByMBean() {
String portStr = null;
MBeanServer mBeanServer = null;
ArrayList<MBeanServer> mBeanServers = MBeanServerFactory.findMBeanServer(null);
if (mBeanServers.size() > 0) {
mBeanServer = mBeanServers.get(0);
}
if (mBeanServer == null) {
throw new IllegalStateException("没有发现JVM中关联的MBeanServer.");
}
Set<ObjectName> objectNames = 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")) {
portStr = String.valueOf(mBeanServer.getAttribute(objectName, "port"));
break;
}
}
} catch (AttributeNotFoundException e) {
e.printStackTrace();
} catch (InstanceNotFoundException e) {
e.printStackTrace();
} catch (MBeanException e) {
e.printStackTrace();
} catch (ReflectionException e) {
e.printStackTrace();
}
// System.out.println("当前tomcat容器端口>>>" + portStr);
log.info("当前tomcat容器端口>>>" + portStr);
return portStr;
}
}
获得服务器IP地址和Tomcat端口号工具类
最新推荐文章于 2024-01-02 15:53:18 发布