package cn.com.MAC;<br />/**<br /> * 利用Runtime call作業系統的命令,具體的命令取決於不同的作業系統,注意不要調用Runtime.getRuntime().exec(String)介面,要用 Runtime.getRuntime().exec(String[])這個介面,不然複雜命令的執行會有問題。例子如下(拿cpu個數,其他類似):<br /> * 定義命令:<br /> * WindowsCmd ="cmd.exe /c echo %NUMBER_OF_PROCESSORS%";//windows的特殊<br /> * SolarisCmd = {"/bin/sh", "-c", "/usr/sbin/psrinfo | wc -l"};<br /> * AIXCmd = {"/bin/sh", "-c", "/usr/sbin/lsdev -Cc processor | wc -l"};<br /> * HPUXCmd = {"/bin/sh", "-c", "echo /"map/" | /usr/sbin/cstm | grep CPU | wc -l "};<br /> * LinuxCmd = {"/bin/sh", "-c", "cat /proc/cpuinfo | grep ^process | wc -l"};<br /> *<br /> * 然後判斷系統:<br /> * os = System.getProperty("os.name").toLowerCase();<br /> * 根據不同的作業系統call不同的命令。<br /> */<br />import java.io.IOException;<br />import java.io.InputStream;<br />import java.io.InputStreamReader;<br />import java.io.LineNumberReader;<br />public class GetMACAddress {<br />public String getMACAddress(String ipAddress) {<br />String str = "", strMAC = "", macAddress = "";<br />try {<br />Process pp = Runtime.getRuntime().exec("nbtstat -a " + ipAddress);<br />InputStreamReader ir = new InputStreamReader(pp.getInputStream());<br />LineNumberReader input = new LineNumberReader(ir);<br />for (int i = 1; i < 100; i++) {<br />str = input.readLine();<br />if (str != null) {<br />if (str.indexOf("MAC Address") > 1) {<br />strMAC = str.substring(str.indexOf("MAC Address") + 14,<br />str.length());<br />break;<br />}<br />}<br />}<br />} catch (IOException ex) {<br />return "Can't Get MAC Address!";<br />}<br />//<br />if (strMAC.length() < 17) {<br />return "Error!";<br />}<br />macAddress = strMAC.substring(0, 2) + ":" + strMAC.substring(3, 5)<br />+ ":" + strMAC.substring(6, 8) + ":" + strMAC.substring(9, 11)<br />+ ":" + strMAC.substring(12, 14) + ":"<br />+ strMAC.substring(15, 17);<br />//<br />return macAddress;<br />}<br />public static void main(String[] args) {<br />GetMACAddress getMACAddress = new GetMACAddress();<br />//System.out.println(getMACAddress.getMACAddress("172.18.8.225"));//00-50-56-C0-00-08<br />System.out.println("MAC地址:"+getMACAddress.getMACAddress("192.168.0.101"));<br />try {<br />java.lang.Process proc = Runtime.getRuntime().exec("ipconfig /all");<br />InputStream istr = proc.getInputStream();<br />byte[] data = new byte[1024];<br />istr.read(data);<br />String netdata = new String(data);<br />System.out.println("Your Mac Address=" + procAll(netdata));<br />} catch (IOException e) {<br />System.out.println("error=" + e);<br />}<br />}<br />public static String procAll(String str) {<br />return procStringEnd(procFirstMac(procAddress(str)));<br />}<br />public static String procAddress(String str) {<br />int indexof = str.indexOf("Physical Address");<br />if (indexof > 0) {<br />return str.substring(indexof, str.length());<br />}<br />return str;<br />}<br />public static String procFirstMac(String str) {<br />int indexof = str.indexOf(":");<br />if (indexof > 0) {<br />return str.substring(indexof + 1, str.length()).trim();<br />}<br />return str;<br />}<br />public static String procStringEnd(String str) {<br />int indexof = str.indexOf("/r");<br />if (indexof > 0) {<br />return str.substring(0, indexof).trim();<br />}<br />return str;<br />}<br />}<br />
按照這個方法可以擷取本地MAC地址,不管你是否安裝虛擬機器都可以擷取“真正的”MAC地址,方法:
System.out.println("MAC地址:"+getMACAddress.getMACAddress("192.168.0.101"));
還有如下一種方法:
package cn.com.e52.util;<br />import java.io.*;<br />import java.util.*;<br />import java.util.regex.*;<br />public class HardwareID {<br />String IPCONFIG_COMMAND_WIN = "ipconfig /all";<br />boolean realMac = true;<br />String unique = "";<br />public static String getMacAddress() {<br />HardwareID hwid = new HardwareID();<br />String aa[]=hwid.getUnique().trim().split("#");<br />return aa[2];<br />//return hwid.getUnique().trim();<br />}<br />private String getUnique() {<br />String os = System.getProperty("os.name");<br />if (os.startsWith("Windows")) {<br />return getUniqueWindows();<br />} else {<br />return "";<br />}<br />}<br />private String getUniqueWindows() {<br />// 運行控制台命令,返回結果字串<br />String ipConfigResponse = null;<br />try {<br />ipConfigResponse = runConsoleCommand(IPCONFIG_COMMAND_WIN);<br />} catch (IOException e) {<br />e.printStackTrace();<br />}<br />// 按行分割結果字串,並迴圈判斷每個字串直道找出 Mac 地址<br />StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "/n");<br />while (tokenizer.hasMoreTokens()) {<br />String line = tokenizer.nextToken().trim();<br />// 擷取每行 ":" 後的字串<br />int macAddressPosition = line.indexOf(":");<br />if (macAddressPosition <= 0) {<br />continue;<br />}<br />String macAddressCandidate = line.substring(macAddressPosition + 1)<br />.trim();<br />// 檢查 macAddressCandidate 中內容是否為真實網卡 Mac 地址,根據 Mac 地址計算出唯一標識。<br />if (isMacAddWin(macAddressCandidate)) {<br />if (realMac == true) {<br />generateUnique(macAddressCandidate);<br />} else {<br />realMac = true;<br />}<br />}<br />}<br />return unique;<br />}<br />/**<br /> * 運行控制台命令,返回結果字串<br /> *<br /> * @param command<br /> * String<br /> * @return String<br /> * @throws IOException<br /> */<br />private String runConsoleCommand(String command) throws IOException {<br />Process p = Runtime.getRuntime().exec(command);<br />InputStream stdoutStream = new BufferedInputStream(p.getInputStream());<br />StringBuffer buffer = new StringBuffer();<br />while (true) {<br />int c = stdoutStream.read();<br />if (c == -1) {<br />break;<br />}<br />buffer.append((char) c);<br />}<br />String outputText = buffer.toString();<br />stdoutStream.close();<br />return outputText;<br />}<br />/**<br /> * 對輸入參數進行檢查,符合Regex的為 windows 平台下有效 Mac 地址<br /> *<br /> * @param macAddressCandidate<br /> * String<br /> * @return boolean<br /> */<br />private boolean isMacAddWin(String macAddressCandidate) {<br />Pattern macPattern = Pattern<br />.compile("[0-9a-fA-F]{2}-[0-9a-fA-F]{2}-[0-9a-fA-F]{2}-[0-9a-fA-F]{2}-[0-9a-fA-F]{2}-[0-9a-fA-F]{2}");<br />Matcher m = macPattern.matcher(macAddressCandidate);<br />return m.matches();<br />}<br />///**<br />// * 對輸入參數進行檢查,符合長度的為 MAC OS X 下有效網卡 Mac 地址<br />// *<br />// * @param macAddressCandidate<br />// * String<br />// * @return boolean<br />// */<br />//private boolean isMacAddOSX(String macAddressCandidate) {<br />//if (macAddressCandidate.length() != 17) {<br />//return false;<br />//} else {<br />//return true;<br />//}<br />//}<br />/**<br /> * 產生 Unique<br /> *<br /> * @param macAddress<br /> * String<br /> */<br />private void generateUnique(String macAddress) {<br />if (unique == "") {<br />unique += macAddress;<br />} else {<br />unique += "#";<br />unique += macAddress;<br />}<br />}<br />public static void main(String[] args) {<br />System.out.println(HardwareID.getMacAddress()); //這裡做了一次處理,主要是我這裡安裝了虛擬機器,有多個MAC地址。<br />}<br />}