如何获得机器的mac地址 [英] how to get machines mac address

查看:103
本文介绍了如何获得机器的mac地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want get machines' MAC address..but below written code only display the MAC address when Internet is connected to my machine other it will return null... I am using windows 7

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();
        }
    }
}


推荐答案

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

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();
    }

}

这篇关于如何获得机器的mac地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆