当前位置:首页 > 操作系统 > MacOs

java – 如何获取机器的mac地址

我想得到机器的MAC地址..但是下面写的代码只显示互联网连接到我的机器的MAC地址,否则它将返回null …我正在使用Windows 7

<code>import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

class test
{
    public static void main(String[] args)
    {
        InetAddress ip;
        try {
            ip = InetAddress.getLocalHost();

            System.out.println("The mac Address of this machine is :" + ip.getHostAddress());

            NetworkInterface network = NetworkInterface.getByInetAddress(ip);

            byte[] mac = network.getHardwareAddress();

            System.out.print("The mac address is : ");

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++){
                sb.append(String.format("%02X%s", mac[i],(i< mac.length - 1)?"-":""));
            }

            System.out.println(sb.toString());

        } 
        catch (UnknownHostException e) {
            e.printStackTrace();
        } 
        catch (SocketException e) {
            e.printStackTrace();
        }
    }
}
</code>

解决方法:

试试这个应该适用于Linux和Windows

<code>public static void main(String[] args) {

    String command = "/sbin/ifconfig";

    String sOsName = System.getProperty("os.name");
    if (sOsName.startsWith("Windows")) {
        command = "ipconfig";
    } else {

        if ((sOsName.startsWith("Linux")) || (sOsName.startsWith("Mac"))
                || (sOsName.startsWith("HP-UX"))) {
            command = "/sbin/ifconfig";
        } else {
            System.out.println("The current operating system '" + sOsName
                    + "' is not supported.");
        }
    }

    Pattern p = Pattern
            .compile("([a-fA-F0-9]{1,2}(-|:)){5}[a-fA-F0-9]{1,2}");
    try {
        Process pa = Runtime.getRuntime().exec(command);
        pa.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                pa.getInputStream()));

        String line;
        Matcher m;
        while ((line = reader.readLine()) != null) {

            m = p.matcher(line);

            if (!m.find())
                continue;
            line = m.group();
            break;

        }
        System.out.println(line);
    } catch (Exception e) {
        e.printStackTrace();
    }

}
</code>

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐