JAVA獲取本機MAC地址

爲什麼寫這個呢?因爲MAC可用於局域網驗證,提高安全性。

  1. /**
  2.  * 獲取mac地址
    物理地址是48位,別和ipv6搞錯了
  3.  * @author Administrator
  4.  *
  5.  */
  6. public class Test {
  7.     
  8.         /**
  9.          * @param args
  10.          * @throws UnknownHostException
  11.          * @throws SocketException
  12.          */
  13.         public static void main(String[] args) throws UnknownHostException, SocketException {
  14.             // TODO Auto-generated method stub
  15.             
  16.             //得到IP,輸出PC-201309011313/122.206.73.83
  17.             InetAddress ia = InetAddress.getLocalHost();
  18.             System.out.println(ia);
  19.             getLocalMac(ia);
  20.         }
  21.         private static void getLocalMac(InetAddress ia) throws SocketException {
  22.             // TODO Auto-generated method stub
  23.             //獲取網卡,獲取地址
  24.             byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
  25.             System.out.println("mac數組長度:"+mac.length);
  26.             StringBuffer sb = new StringBuffer("");
  27.             for(int i=0; i<mac.length; i++) {
  28.                 if(i!=0) {
  29.                     sb.append("-");
  30.                 }
  31.                 //字節轉換爲整數
  32.                 int temp = mac[i]&0xff;
  33.                 String str = Integer.toHexString(temp);
  34.                 System.out.println("每8位:"+str);
  35.                 if(str.length()==1) {
  36.                     sb.append("0"+str);
  37.                 }else {
  38.                     sb.append(str);
  39.                 }
  40.             }
  41.             System.out.println("本機MAC地址:"+sb.toString().toUpperCase());
  42.         }
  43.     
  44. }

 

  運行結果如下:

PC-201309011313/122.206.73.83
mac數組長度:6
每8位:d0
每8位:27
每8位:88
每8位:1f
每8位:89
每8位:51
本機MAC地址:D0-27-88-1F-89-51
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章