转:获取客户端网卡的MAC地址

教程由JAVA中文网整理校对发布(javaweb.cc)

1.获取客户端ip地址( 这个必须从客户端传到后台):
jsp页面下,很简单,request.getRemoteAddr() ;
因为系统的VIew层是用JSF来实现的,因此页面上没法直接获得类似request,在bean里做了个强制转换


1. public String getMyIP() { 
2. try { 
3. FacesContext fc = FacesContext.getCurrentInstance(); 
4. HttpServletRequest request = (HttpServletRequest)fc.getExternalContext().getRequest(); 
5. return request.getRemoteAddr(); 
6. } 
7. catch (Exception e) { 
8. e.printStackTrace(); 
9. } 
10. return ""; 
11. }


2.获取客户端mac地址
调用window的命令,在后台Bean里实现 通过ip来获取mac地址。方法如下:


1. //运行速度【快】 
2. public String getMAC() { 
3. String mac = null; 
4. try { 
5. Process pro = Runtime.getRuntime().exec("cmd.exe /c ipconfig/all"); 
6. 
7. InputStream is = pro.getInputStream(); 
8. BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
9. String message = br.readLine(); 
10. 
11. int index = -1; 
12. while (message != null) { 
13. if ((index = message.indexOf("Physical Address")) > 0) { 
14. mac = message.substring(index + 36).trim(); 
15. break; 
16. } 
17. message = br.readLine(); 
18. } 
19. System.out.println(mac); 
20. br.close(); 
21. pro.destroy(); 
22. } catch (IOException e) { 
23. System.out.println("Can't get mac address!"); 
24. return null; 
25. } 
26. return mac; 
27. } 
28. 
29. //运行速度【慢】 
30. public String getMAC(String ip){ 
31. String str = null; 
32. String macAddress = null; 
33. try { 
34. Process p = Runtime.getRuntime().exec("nbtstat -A " + ip); 
35. InputStreamReader ir = new InputStreamReader(p.getInputStream()); 
36. LineNumberReader input = new LineNumberReader(ir); 
37. for (; true; ) { 
38. str = input.readLine(); 
39. if (str != null) { 
40. if (str.indexOf("MAC Address") > 1) { 
41. macAddress = str.substring(str.indexOf("MAC Address") + 14); 
42. break; 
43. } 
44. } 
45. } 
46. } catch (IOException e) { 
47. e.printStackTrace(System.out); 
48. return null; 
49. } 
50. return macAddress; 
51. }



获取客户端网卡的MAC地址(本教程仅供研究和学习,不代表JAVA中文网观点)
本篇文章链接地址:http://javaweb.cc/other/code/181588.shtml
如需转载请注明出自JAVA中文网:http://www.javaweb.cc/
原文地址:https://www.cnblogs.com/mabaishui/p/2172497.html