我在網上找了一下獲取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地址拼裝成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();
}
這種方法貌似是隻能取本機的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",所以可能需要自己做一些調整。