我在網上找了一下擷取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地址的兩種方法(推薦)全部內容了,希望大家多多支援雲棲社區~