<span style="white-space:pre"> </span>/** * 取客户端MAC地址 * @author huangwg 2014-06-26 */ public static String getMACAddress(HttpServletRequest request) { String macAddress = ""; String ip = getClientIPAddress(request); Properties props = System.getProperties(); if(props.get("os.name").toString().contains("Window")){ //判断操作系统 if(ip.equals("127.0.0.1")){ //本机的IP地址查询不了,要转成192.xxx.xxx.xxx的形式 InetAddress addr = null; try { addr = InetAddress.getLocalHost(); ip=addr.getHostAddress().toString(); } catch (UnknownHostException e) { ip = "127.0.0.1"; } } String str = ""; try { Process p = Runtime.getRuntime().exec("nbtstat -A " + ip); InputStreamReader ir = new InputStreamReader(p.getInputStream()); LineNumberReader input = new LineNumberReader(ir); for (int i = 1; i < 100; i++) { str = input.readLine(); if (str != null) { if (str.contains("MAC Address")) { macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length()); break; }else if(str.contains("MAC 地址")){ //有的机器会显示中文 macAddress = str.substring(str.indexOf("MAC 地址") + 9, str.length()); break; } } } } catch (IOException e) { return ""; } } else { try { Runtime.getRuntime().exec("ping -c1 " + ip); Process p = Runtime.getRuntime().exec( new String[] { "/bin/sh", "-c", "arp | grep " + ip + " | awk '{print $3}'" }); InputStreamReader ir = new InputStreamReader(p.getInputStream()); LineNumberReader input = new LineNumberReader(ir); macAddress = input.readLine(); } catch (IOException e) { return ""; } } return macAddress; }
在网上找到了两种方案,一种是通过js来获取,但是由于IE安全性的问题会有弹出提示框,让客户设备很麻烦所以放弃了。
一种是能过java代码,在网上只找到在window下的,没有Linux的,所以改良了一下。