package com.whj.common.util;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectName;
public class IpUtils {
/**
* windows服务器ip
*
* @return
* @throws UnknownHostException
*/
public static String getWindowsLocalIp() throws UnknownHostException {
return InetAddress.getLocalHost().getHostAddress();
}
/**
* linux服务器ip
*
* @return
* @throws UnknownHostException
*/
public static String getLinuxLocalIp() throws SocketException {
InetAddress ip = null;
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
// ----------特定情况,可以考虑用ni.getName判断
String name = ni.getName();
// System.out.println("name:》》"+name);
if (name.contains("docker") || name.contains("lo")) {
continue;
}
// 遍历所有ip
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
ip = (InetAddress) ips.nextElement();
// System.out.println("ip:>>"+ip);
String hostAddress = ip.getHostAddress();
// System.out.println("hostAddress:>>"+hostAddress);
if ((hostAddress.endsWith(".0")) || (hostAddress.endsWith(".1"))) {
continue;
}
if (hostAddress.contains("::") || hostAddress.contains("0:0:") || hostAddress.contains("fe80")) {
continue;
}
// 127.开头的都是lookback地址
if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
// System.out.println(" target:>>"+ip);
return hostAddress;
}
}
}
throw new RuntimeException("Failed to get the server ip");
}
/**
* 判断操作系统是否是Windows
*
* @return
*/
public static boolean isWindowsOS() {
boolean isWindowsOS = false;
// 注:这里的system,系统指的是 JRE (runtime)system,不是指 OS
String osName = System.getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}
/**
* 获取本地IP地址
*
* @throws SocketException
*/
public static String getLocalIP() throws UnknownHostException, SocketException {
if (isWindowsOS()) {
return getWindowsLocalIp();
} else {
return getLinuxLocalIp();
}
}
public static String getMac() throws Exception {
InetAddress ia = InetAddress.getLocalHost();
// 获取网卡,获取地址
byte[] mac = NetworkInterface.getByInetAddress(ia).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);
// System.out.println("每8位:"+str);
if (str.length() == 1) {
sb.append("0" + str);
} else {
sb.append(str);
}
}
return sb.toString().toUpperCase();
}
public static String getPort() throws Exception {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> objectNames = mBeanServer.queryNames(new ObjectName("*:type=Connector,*"), null);
if (objectNames == null || objectNames.size() <= 0) {
throw new IllegalStateException("Cannot get the names of MBeans controlled by the MBean server.");
}
for (ObjectName objectName : objectNames) {
String protocol = String.valueOf(mBeanServer.getAttribute(objectName, "protocol"));
String port = String.valueOf(mBeanServer.getAttribute(objectName, "port"));
// windows下属性名称为HTTP/1.1, linux下为org.apache.coyote.http11.Http11NioProtocol
if (protocol.equals("HTTP/1.1") || protocol.equals("org.apache.coyote.http11.Http11NioProtocol")) {
return port;
}
}
throw new IllegalStateException("Failed to get the HTTP port of the current server");
}
/**
* 根据ip+端口号生成key
*
* <p>无法获取ip和port时随机生成key
* @return
*/
public static String getServerKey(){
String ip=null;
String port=null;
try {
ip=getLocalIP();
}catch(Exception e) {
e.printStackTrace();
}
if(ip==null) {
try {
ip=getMac();
}catch(Exception e) {
e.printStackTrace();
ip=RandomUtils.genarateStr(6, "SVR-");
}
}
try {
port=getPort();
}catch(Exception e) {
e.printStackTrace();
port=RandomUtils.genarateNumStr(4, null);
}
return ip+":"+port;
}
public static void main(String[] args) throws Exception {
System.out.println(getWindowsLocalIp());
System.out.println(getLinuxLocalIp());
System.out.println(getMac());
System.out.println(getServerKey());
}
}