转自:https://www.cnblogs.com/ningJJ/p/10997448.html
package com.movitech.product.datahub.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.util.Set;
/**
-
@author Jay
-
@date 2019/06/10
*/
public class CommonUtils {private static final Logger logger = LoggerFactory.getLogger(CommonUtils.class);
public static void main(String[] args){
System.out.println(getLocalIP());
System.out.println(getLocalPort());
}/**
-
@return
-
@throws MalformedObjectNameException
-
获取当前机器的端口号
*/
public static String getLocalPort(){MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
Set objectNames = null;
try {
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;
} catch (MalformedObjectNameException e) {
e.printStackTrace();
}
return null;
}
/**
-
@return
-
获取当前机器的 IP
*/
public static String getLocalIP() {
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (Exception e) {
e.printStackTrace();
}byte[] ipAddr = addr.getAddress();
String ipAddrStr = "";
for (int i = 0; i < ipAddr.length; i++) {
if (i > 0) {
ipAddrStr += ".";
}
ipAddrStr += ipAddr[i] & 0xFF;
}
return ipAddrStr;
}
-
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于