All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zcj.util.UtilPc Maven / Gradle / Ivy

There is a newer version: 1.1.38
Show newest version
package com.zcj.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.management.VMManagement;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Formatter;
import java.util.Locale;

public class UtilPc {

    private static final Logger logger = LoggerFactory.getLogger(UtilPc.class);

    /**
     * 获取电脑的MAC地址,如:78-E3-B5-A5-F5-B3
     *
     * @return 如果获取失败,则返回8位随机数
     */
    public static String getMac() {
        try (Formatter formatter = new Formatter()) {
            InetAddress address = InetAddress.getLocalHost();
            NetworkInterface ni = NetworkInterface.getByInetAddress(address);
            byte[] mac = ni.getHardwareAddress();
            String sMac = "";
            for (int i = 0; i < mac.length; i++) {
                sMac = formatter.format(Locale.getDefault(), "%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")
                        .toString();
            }
            return sMac;
        } catch (Exception e) {
            logger.warn("获取MAC地址失败,将使用8位随机数替代");
        }
        return UtilRandom.getRandomChar(8);
    }

    /**
     * 获取主机名称
     *
     * @return 如果获取失败,则返回NULL
     */
    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
        }
        return null;
    }

    /**
     * 获取主机IP地址
     *
     * @return 如果获取失败,则返回NULL
     */
    public static String getHostAddress() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
        }
        return null;
    }

    /**
     * 获取JVM进程ID
     *
     * @return 如果获取失败,则返回NULL
     **/
    public static Integer jvmPid() {
        try {
            RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
            Field jvm = runtime.getClass().getDeclaredField("jvm");
            jvm.setAccessible(true);
            VMManagement mgmt = (VMManagement) jvm.get(runtime);
            Method pidMethod = mgmt.getClass().getDeclaredMethod("getProcessId");
            pidMethod.setAccessible(true);
            return (Integer) pidMethod.invoke(mgmt);
        } catch (Exception var4) {
        }
        return null;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy