如何获得机器的mac地址

时间:2012-08-09 13:37:25

标签: java

我想获取机器的MAC地址..但是下面写的代码只显示互联网连接到我的机器时的MAC地址,否则它将返回null ...我正在使用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();
        }
    }
}

3 个答案:

答案 0 :(得分:6)

试试这个它应该适用于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();
    }

}

答案 1 :(得分:5)

好像你正试图通过IP地址获取MAC地址。当您成功连接到Internet时,IP地址。否则,正如您所述,它将是null

试试这个:NetworkInterface.getHardwareAddress()

如果您需要计算机上所有网络接口的MAC地址,请尝试以下操作:NetworkInterface.getNetworkInterfaces()


编辑:再次审核代码后,我意识到您已实施我的建议。但是,您只是尝试获取MAC地址如果您拥有有效的IP。如果没有连接到Internet,您将没有有效的IP。

   public static void main(String[] args) 
   { 
       NetworkInterface network;
       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());  
   } 

答案 2 :(得分:2)

问题可能是由于当您的计算机未连接到Internet时,您的网卡没有分配的IP地址。您正试图通过IP地址查找网络接口。

我建议您枚举所有网络接口,然后选择您需要的接口:

import java.net.*;
import java.util.*;

public class App {

    protected static String formatMac(byte[] mac) {
        if (mac == null)
            return "UNKNOWN";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
        }
        return sb.toString();
    }

   public static void main(String[] args) throws Exception {
       for(Enumeration<NetworkInterface> e
                    = NetworkInterface.getNetworkInterfaces();
               e.hasMoreElements(); )
       {
           NetworkInterface ni = e.nextElement();
           System.out.println(ni.getName() + " - " + formatMac(ni.getHardwareAddress()));
       }
   }
}

这可以解决问题,无需任何互联网连接即可正常工作。