我在網上找了一下獲取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地址的兩種方法(推薦)全部內容了,希望大家多多支持武林網~
新聞熱點
疑難解答