Java obtains client mac address
question
A function needs to be implemented in the project. When the user logs in, the system account is required to be bound to the computer. Only the bound account can be logged in, and each account can only be bound to one computer.
Solution
Get the mac address by requesting IP, and then bind the account to the mac address.
The code implementation is as follows:
String getMacInfo(HttpServletRequest request) { //Get the IP address String macInfo = null; try { String ip = (); //Get mac address under linux macAddr = (ip); //Get mac address under windows if((macAddr)){ macAddr = (ip).trim(); } } catch (Exception e) { ("Failed to get mac address"); return null; } return macInfo; }
// Get mac address from a Unix machine public static String getMac(String ip) throws IOException { String mac = ; if (ip != null) { try { Process process = ().exec("arp "+ip); InputStreamReader ir = new InputStreamReader(()); LineNumberReader input = new LineNumberReader(ir); String line; StringBuffer s = new StringBuffer(); while ((line = ()) != null) { (line); } mac = (); if ((mac)) { mac = ((":") - 2, (":") + 3); } return mac; } catch (Exception e) { (); } } return mac; } // Get the mac address from the windows machine public static String getMacInWindows(final String ip) { String result = ""; String[] cmd = {"cmd", "/c", "ping " + ip}; String[] another = {"cmd", "/c", "ipconfig -all"}; // Get the result after executing the command String cmdResult = callCmd(cmd, another); // Get the mac address from the result of the previous step result = filterMacAddress(ip, cmdResult, "-"); return result; } // Command execution public static String callCmd(String[] cmd, String[] another) { String result = ""; String line = ""; try { Runtime rt = (); // Execute the first command Process proc = (cmd); (); // Execute the second command proc = (another); InputStreamReader is = new InputStreamReader(()); BufferedReader br = new BufferedReader(is); while ((line = ()) != null) { result += line; } } catch (Exception e) { (); } return result; } // Get the mac address public static String filterMacAddress(final String ip, final String sourceString, final String macSeparator) { String result = ""; String regExp = "((([0-9,A-F,a-f]{1,2}" + macSeparator + "){1,5})[0-9,A-F,a-f]{1,2})"; Pattern pattern = (regExp); Matcher matcher = (sourceString); while (()) { result = (1); // Due to the problem of multiple network cards of the computer, the first mac address that is close to the IP is intercepted. int num = (ip) - (": "+result + " "); if (num>0&&num<300) { break; } } return result; }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.