JDK6新特性,JAVA获得机器MAC地址的方法
这个代码包含了以前常见的用Runtime实现的方法,已经使用JDK1.6新特性实现的方法。
1.import java.io.BufferedReader; 2.import java.io.InputStreamReader; 3.import java.net.NetworkInterface; 4.import java.util.Enumeration; 5./** 6. * JDK6新特性,JAVA获得机器MAC地址的方法 7. * 8. * @author 老紫竹(Java世纪网,java2000.net) 9. */ 10.publicclass Test { 11. // 返回一个字节的十六进制字符串 12. static String hexByte(byte b) { 13. String s = "000000" + Integer.toHexString(b); 14. return s.substring(s.length() - 2); 15. } 16. publicstaticvoid main(String[] args) throws Exception { 17. System.out.println("本机器的所有的网卡MAC发下:"); 18. getMacOnWindow(); 19. getMac(); 20. } 21. /** 22. * JDK1.6新特性获取网卡MAC地址 23. */ 24. publicstaticvoid getMac() { 25. try { 26. Enumeration<NetworkInterface> el = NetworkInterface.getNetworkInterfaces(); 27. while (el.hasMoreElements()) { 28. byte[] mac = el.nextElement().getHardwareAddress(); 29. if (mac == null) 30. continue; 31. StringBuilder builder = new StringBuilder(); 32. for (byte b : mac) { 33. builder.append(hexByte(b)); 34. builder.append("-"); 35. } 36. builder.deleteCharAt(builder.length() - 1); 37. System.out.println(builder); 38. } 39. } catch (Exception exception) { 40. exception.printStackTrace(); 41. } 42. } 43. /** 44. * 原始的获取网卡MAC地址 45. */ 46. publicstaticvoid getMacOnWindow() { 47. try { 48. String mac = null; 49. Process process = Runtime.getRuntime().exec("ipconfig /all"); 50. BufferedReader buffer = new BufferedReader(new InputStreamReader(process.getInputStream())); 51. for (String line = buffer.readLine(); line != null; line = buffer.readLine()) { 52. int index = line.indexOf("Physical Address"); 53. if (index <= 0) { 54. continue; 55. } 56. mac = line.substring(index + 36); 57. break; 58. } 59. buffer.close(); 60. process.waitFor(); 61. System.out.println(mac); 62. } catch (Exception exception) { 63. exception.printStackTrace(); 64. } 65. } 66.}