java 擷取mac地址的兩種方法(推薦)_java

來源:互聯網
上載者:User

我在網上找了一下擷取mac地址的方法,找了兩種比較不太一樣的方法。

第一種

public static void main(String[] args) throws Exception {InetAddress ia = InetAddress.getLocalHost();System.out.println(getMACAddress(ia));}
private static String getMACAddress(InetAddress ia) throws Exception {// 獲得網路介面對象(即網卡),並得到mac地址,mac地址存在於一個byte數組中。byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();// 下面代碼是把mac地址拼裝成StringStringBuffer 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();}

這種方法貌似是只能取原生mac地址的。

第二種

public static void main(String[] args) throws Exception {getMac("192.168.1.186");}
public static String getMac(String ip){String str = null;String mac = null;try{Process p = Runtime.getRuntime().exec("nbtstat -A " + ip); InputStreamReader ir = new InputStreamReader(p.getInputStream(),"gbk"); LineNumberReader input = new LineNumberReader(ir); for (; true;) { str = input.readLine(); if (str != null) {if (str.indexOf("MAC 位址") > 1) {mac = str.substring(str.indexOf("MAC 位址") + 9);break; }}}System.out.println(mac);}catch(IOException e){e.printStackTrace();}return mac;}

這種方法是我比較喜歡的,不過這種方法呢在時間效率上可能會稍差一些。這個裡面有一個比較需要注意的點就是資料流那裡記得要改成gbk格式的,不然讀出來的資料是亂碼的,後面就會無法進行了,然後識別欄位那裡,可能有一些會是"MAC address",所以可能需要自己做一些調整。

以上就是小編為大家帶來的java 擷取mac地址的兩種方法(推薦)全部內容了,希望大家多多支援雲棲社區~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.