首页 > 代码库 > 获取MAC地址

获取MAC地址

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;


import org.apache.commons.codec.digest.DigestUtils;


import com.yd.common.utils.StringUtils;
 
/**
 * 
 * @author MrWang
 * 获取客户端MAC地址
 * 
 *
 */
 
public class MacAddress {
     
private static String mac_s = "";


    static {
    if (mac_s == "") {
       Enumeration<NetworkInterface> el;
       try {
           el = NetworkInterface.getNetworkInterfaces();
           while (el.hasMoreElements()) {
             NetworkInterface networkInterface = el.nextElement();
               byte[] mac = networkInterface.getHardwareAddress();
               if (mac == null||mac.length==0)
                   continue;
               if (mac.length==6) {
                   mac_s = hexByte(mac[0]) + "-" + hexByte(mac[1]) + "-"
                           + hexByte(mac[2]) + "-" + hexByte(mac[3]) + "-"
                           + hexByte(mac[4]) + "-" + hexByte(mac[5]);
                   System.out.println(mac_s);
                   //mac_s = DigestUtils.md5Hex(mac_s).toUpperCase().substring(0, 8);
                   //System.out.println(mac_s);
                   
                   break;
               }
           }
       } catch (SocketException e1) {
           e1.printStackTrace();
       }
      
       }
    }
    
    public static String hexByte(byte b) {
        String s = "00" + Integer.toHexString(b);
        return s.substring(s.length() - 2);
    }
    
    public static  String getMAC() {
        return mac_s;
    }
     
    public static void main(String[] args) {
        MacAddress m = new MacAddress();
        m.getMAC();
         
    }
}

 

获取MAC地址