java two ways to get an mac address are recommended by of

  • 2020-05-10 18:09:15
  • OfStack

I looked for a method to get the mac address on the Internet, and found two different methods.

1 kind


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 {
//  Gets the network interface object (that is, the network card) and gets mac The address, mac The address exists at 1 a byte In the array. 
byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();

//  The following code is put mac The address is assembled into String
StringBuffer sb = new StringBuffer();

for (int i = 0; i < mac.length; i++) {
if (i != 0) {
sb.append("-");
}
// mac[i] & 0xFF  Is for the sake of the byte It turns into a positive integer 
String s = Integer.toHexString(mac[i] & 0xFF);
sb.append(s.length() == 1 ? 0 + s : s);
}

//  Change all lowercase letters of a string to uppercase to make them normal mac Address and return 
return sb.toString().toUpperCase();
}

This method seems to take only the mac address of the machine.

2 kinds of


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  address ") > 1) {
mac = str.substring(str.indexOf("MAC  address ") + 9);
break; 
}
}
}
System.out.println(mac);
}catch(IOException e){
e.printStackTrace();
}
return mac;
}

That's the way I like it, but it's a little bit less time efficient. One of the important points to pay attention to is that the data flow should be changed to gbk format, otherwise the data will be scrambled, and then it will be impossible to carry out the process. Then, there may be 1 "MAC address" in the recognition field, so you may need to make some adjustment by yourself.


Related articles: