Java如何获取客户端mac地址
目录
- Java获取客户端MAC地址
- 问题
- 解决方案
- 总结
Java获取客户端mac地址
问题
项目中需要实现一个功能,在用户登录的时候,要求系统编程账号和计算机绑定,只有绑定的账号才可以登录,并且每个账号只能绑定一台计算机。
解决方案
通过请求IP获取mac地址,然后将账号与mac地址进行绑定。
代码实现如下:
String getMacInfo(HttpServletRequest request) { //获取ip地址 String macInfo = null; try { String ip = request.getRemoteAddr(); //linux下获取mac地址 macAddr = CommonUtils.getMac(ip); //Windows下获取mac地址 if(StringUtils.isBlank(macAddr)){ macAddr = CommonUtils.getMacInWindows(ip).trim(); } } catch (Exception e) { log.error("获取mac地址失败"); return null; } return macInfo; }
CommonUtils.java
// 从类Unix机器上获取mac地址 public static String getMac(String ip) throws IOException { String mac = SysCode.BDFH.EMPTY; if (ip != null) { try { php Process process = Runtime.getRuntime().exec("arp "+ip); InputStreamReader ir = new InputStreamReader(process.getInputStream()); LineNumberReader input = new LineNumberReader(ir); String line; StringBuffer s = new StringBuffer(); while ((line = input.readLine()) != null) { s.append(line); } mac = s.toString(); if (StringUtils.isNotBlank(mac)) { mac = mac.substring(mac.indexOf(":") - 2, mac.lastIndexOf(":") + 3); } return mac; } catch (Exception e) { e.printStackTrace(); } } return mac; } // 从windows机器上获取mac地址 public static String getMacInWindows(final String ip) { String result = ""; String[] cmd = {"cmd", "/c", "ping " + ip}; String[] another = {"cmd", "/c", "ipconfig -all"}; // 获取执行命令后的result String cmdResult = callCmd(cmd, another); // 从上一步的结果中获取mac地址 result = filterMacAddress(ip, cmdResult, "-"); return result; } // 命令执行 public static String callCmd(String[编程客栈] cmd, String[] another) { String result = ""; String line = ""; try { Runtime rt = Runtime.getRuntime(); // 执行第一个命令 Process proc = rt.exec(cmd); proc.waitFor(); // 执行第二个命令 proc = rt.exec(another); InputStreamReader is = new InputStreamReader(proc.getInputStream()); BufferedReader br = new BufferedReader(is); while ((line = br.readLine()) != null) { result += line; } } catch (Exception e) php{ e.printStackTrace(); } return result; } // 获取mac地址 public static String filterMacAddress(final String ip, final String sourceString, final St编程客栈ring 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 = Pattern.compile(regExp); Matcher matcher = pattern.matcher(sourceString); while (matcher.find()) { result = matcher.group(1); // 因计算机多网卡问题,截取紧靠IP后的第一个mac地址 int num = sourceString.indexOf(ip) - sourceString.indexOf(": "+result + " "); if (num>0&&num<300) { break; } } return result; }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
精彩评论