I looked for a way to get the mac address online and found two different methods.
The first type
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 {// Get the network interface object (i.e. network card) and get the mac address, which exists in a byte array. byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();// The following code is to assemble the mac address into StringStringBuffer sb = new StringBuffer();for (int i = 0; i < mac.length; i++) {if (i != 0) {sb.append("-");}// mac[i] & 0xFF is to convert byte into a positive integer String s = Integer.toHexString(mac[i] & 0xFF);sb.append(s.length() == 1 ? 0 + s : s);}// Change all lowercase letters of the string to uppercase and become a regular mac address and return sb.toString().toUpperCase();}This method seems to be able to only get the Mac address of the machine.
The second type
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;}I prefer this method, but this method may be slightly less time-efficient. There is a point that needs to be paid attention to in this. Remember to change the data stream to gbk format, otherwise the read data will be garbled and will not be able to proceed later. Then identify the fields. Some may be "MAC address", so you may need to make some adjustments yourself.
The above are all the two methods (recommended) to obtain mac addresses in Java brought to you by the editor. I hope everyone can support Wulin.com more~