jdk內部方法獲取本機MAC地址

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

public class LocalMac {

    public static void main(String[] args) throws UnknownHostException, SocketException {
        InetAddress ia = InetAddress.getLocalHost();
        System.out.println(ia);
        System.out.println("本機mac地址:" + getLocalMac(ia));
    }
    private static String getLocalMac(InetAddress ia) throws SocketException {
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        // System.out.println("mac數組長度:"+mac.length);
        StringBuffer sb = new StringBuffer("");
        for(int i=0; i<mac.length; i++) {
            if(i!=0) {
                sb.append("-");
            }
            //字節轉換爲整數
            int temp = mac[i]&0xff;
            String str = Integer.toHexString(temp);
            if(str.length()==1) {
                sb.append("0"+str);
            }else {
                sb.append(str);
            }
        }
        return sb.toString().toUpperCase();
    }
}

輸出:html

DESKTOP-NDJUAVS/192.168.43.1
本機mac地址:00-50-56-C0-00-08

參考地址:http://www.cnblogs.com/hxsyl/p/3422191.htmljava

相關文章
相關標籤/搜索