get Mac Address - Java Network

Java examples for Network:Mac Address

Description

get Mac Address

Demo Code


import org.apache.log4j.Logger;
import java.net.NetworkInterface;
import java.net.SocketException;

public class Main{
    private static final Logger logger = Logger.getLogger(MacUtil.class);
    public static String getMacAddress() {
        String MacAddr = "";
        String str = "";
        try {//from   ww  w . j  a v  a 2 s . co m
            NetworkInterface NIC = NetworkInterface.getByName("eth0");
            byte[] buf = NIC.getHardwareAddress();
            if (buf != null) {
                for (int i = 0; i < buf.length; i++) {
                    str = str + byteHEX(buf[i]);
                }
                MacAddr = str.toUpperCase();
            }
        } catch (SocketException e) {
            logger.error("MacUtil -> getMacAddress error !"
                    + e.getMessage());
        }
        return MacAddr;
    }
    public static String byteHEX(byte ib) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        char[] ob = new char[2];
        ob[0] = Digit[(ib >>> 4) & 0X0F];
        ob[1] = Digit[ib & 0X0F];
        String s = new String(ob);
        return s;
    }
}

Related Tutorials