天天看點

純Java獲得本地MAC位址

import java.net.*;

public class Ipconfig{

     public static void main(String[] arguments) throws Exception{

         InetAddress ia = InetAddress.getLocalHost();//擷取本地IP對象

         System.out.println("MAC ......... "+getMACAddress(ia));

     }

     //擷取MAC位址的方法

     private static String getMACAddress(InetAddress ia)throws Exception{

         //獲得網絡接口對象(即網卡),并得到mac位址,mac位址存在于一個byte數組中。

         byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();

         //下面代碼是把mac位址拼裝成String

         StringBuffer sb = new StringBuffer();

         for(int i=0;i<mac.length;i++){

             if(i!=0){

                 sb.append("-");

             }

             //mac[i] & 0xFF 是為了把byte轉化為正整數

             String s = Integer.toHexString(mac[i] & 0xFF);

             sb.append(s.length()==1?0+s:s);

         }

         //把字元串所有小寫字母改為大寫成為正規的mac位址并傳回

         return sb.toString().toUpperCase();

 }若轉載請注明出處!若有疑問,請回複交流!