8

我在获取机器的 mac 地址时遇到问题,在这个问题中使用以下代码解决了这个问题:

Process p = Runtime.getRuntime().exec("getmac /fo csv /nh"); 
java.io.BufferedReader in = new java.io.BufferedReader(new  java.io.InputStreamReader(p.getInputStream())); 
String line; 
line = in.readLine();         
String[] result = line.split(","); 

System.out.println(result[0].replace('"', ' ').trim()); 

但是,我想知道为什么这段代码不起作用。每次读取 MAC 地址时,它都会返回不同的值。首先我认为这是因为 getHash,也许使用了我不知道的时间戳......但即使删除它,结果也会改变。

代码

    public static byte[] getMacAddress() {
        try {
            Enumeration<NetworkInterface> nwInterface = NetworkInterface.getNetworkInterfaces();
            while (nwInterface.hasMoreElements()) {
                NetworkInterface nis = nwInterface.nextElement();
                if (nis != null) {
                    byte[] mac = nis.getHardwareAddress();
                    if (mac != null) {
                        /*
                         * Extract each array of mac address and generate a
                         * hashCode for it
                         */
                        return mac;//.hashCode();
                    } else {
                        Logger.getLogger(Utils.class.getName()).log(Level.WARNING, "Address doesn't exist or is not accessible");
                    }
                } else {
                    Logger.getLogger(Utils.class.getName()).log(Level.WARNING, "Network Interface for the specified address is not found.");
                }
                return null;
            }
        } catch (SocketException ex) {
            Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}

输出示例(我直接从字节数组打印,但足以看出我认为的不同)

[B@91cee
[B@95c083
[B@99681b
[B@a61164
[B@af8358
[B@b61fd1
[B@bb7465
[B@bfc8e0
[B@c2ff5
[B@c8f6f8
[B@d251a3
[B@d6c16c
[B@e2dae9
[B@ef5502
[B@f7f540
[B@f99ff5
[B@fec107

提前致谢

4

4 回答 4

10

B@91cee实际上是数组的结果toString()方法。byte[]

我建议您new String(mac)改为使用打印值。

byte[].toString()实现为:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

由于默认是作为内存中的地址实现的,因此每次Object.hashCode()都创建新的时它并不一致。Object

编辑:

由于返回的字节是十六进制的,所以你应该把它转换成十进制字符串。代码可以从这里看到

于 2012-06-09T15:13:15.360 回答
7

以下是Mkyong.com网站上有关如何在 Java 中获取 MAC 地址的示例:

package com.mkyong;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class app{

   public static void main(String[] args){

    InetAddress ip;
    try {

        ip = InetAddress.getLocalHost();
        System.out.println("Current IP address : " + ip.getHostAddress());

        NetworkInterface network = NetworkInterface.getByInetAddress(ip);

        byte[] mac = network.getHardwareAddress();

        System.out.print("Current MAC address : ");

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

    }

   }

}
于 2012-06-09T15:27:43.930 回答
4

如果机器未连接,西班牙人的答案将不起作用,并且它会根据您连接的网络给出不同的值。

这个不依赖于任何 IP 地址:

public class MacAdress {
    public static void main(String[] args) {
        try {
            InetAddress ip = InetAddress.getLocalHost();
            System.out.println("Current IP address : " + ip.getHostAddress());

            Enumeration<NetworkInterface> networks =
                             NetworkInterface.getNetworkInterfaces();
            while(networks.hasMoreElements()) {
                NetworkInterface network = networks.nextElement();
                byte[] mac = network.getHardwareAddress();

                if (mac != null) {
                    System.out.print("Current MAC address : ");

                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < mac.length; i++) {
                        sb.append(String.format("%02X%s", mac[i],
                                     (i < mac.length - 1) ? "-" : ""));
                    }
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e){
            e.printStackTrace();
        }
    }
}
于 2014-11-13T22:37:24.573 回答
2
public static String getHardwareAddress() throws Exception {
    InetAddress ip = InetAddress.getLocalHost();
    NetworkInterface ni = NetworkInterface.getByInetAddress(ip);
    if (!ni.isVirtual() && !ni.isLoopback() && !ni.isPointToPoint() && ni.isUp()) {
        final byte[] bb = ni.getHardwareAddress();
        return IntStream.generate(ByteBuffer.wrap(bb)::get).limit(bb.length)
                .mapToObj(b -> String.format("%02X", (byte)b))
                .collect(Collectors.joining("-"));
    }
    return null;
}
于 2016-05-12T07:10:15.047 回答