2017-09-20 56 views
-5

獲取MAC地址,我需要從設備獲取MAC地址時,此MAC地址應該是所有類型的這種設備和時間不變的是獨一無二的。我讀了很多話題並嘗試過,但沒有一種方法沒有幫助。以下是我使用的所有方法。如何從設備

從主板:

public static String getMotherboardSN() { 
     String result = ""; 
     try { 
      File file = File.createTempFile("realhowto", ".vbs"); 
      file.deleteOnExit(); 
      FileWriter fw = new java.io.FileWriter(file); 

      String vbs = 
        "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n" 
          + "Set colItems = objWMIService.ExecQuery _ \n" 
          + " (\"Select * from Win32_BaseBoard\") \n" 
          + "For Each objItem in colItems \n" 
          + " Wscript.Echo objItem.SerialNumber \n" 
          + " exit for ' do the first cpu only! \n" 
          + "Next \n"; 

      fw.write(vbs); 
      fw.close(); 
      Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath()); 
      BufferedReader input = 
        new BufferedReader 
          (new InputStreamReader(p.getInputStream())); 
      String line; 
      while ((line = input.readLine()) != null) { 
       result += line; 
      } 
      input.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return result.trim(); 
    } 

從HDD:

public static String getSerialNumber(String drive) { 
     String result = ""; 
     try { 
      File file = File.createTempFile("realhowto",".vbs"); 
      file.deleteOnExit(); 
      FileWriter fw = new java.io.FileWriter(file); 

      String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n" 
        +"Set colDrives = objFSO.Drives\n" 
        +"Set objDrive = colDrives.item(\"C\")\n" 
        +"Wscript.Echo objDrive.SerialNumber"; // see note 
      fw.write(vbs); 
      fw.close(); 
      Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath()); 
      BufferedReader input = 
        new BufferedReader 
          (new InputStreamReader(p.getInputStream())); 
      String line; 
      while ((line = input.readLine()) != null) { 
       result += line; 
      } 
      input.close(); 
     } 
     catch(Exception e){ 
      e.printStackTrace(); 
     } 
     return result.trim(); 
    } 

從CPU:

private static String getWindowsCPU_SerialNumber() { 
     String result = ""; 
     try { 
      File file = File.createTempFile("realhowto",".vbs"); 
      file.deleteOnExit(); 
      FileWriter fw = new java.io.FileWriter(file); 

      String vbs1= 
        "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n" 
          + "Set colItems = objWMIService.ExecQuery _ \n" 
          + " (\"Select * from Win32_Processor\") \n" 
          + "For Each objItem in colItems \n" 
          + " Wscript.Echo objItem.ProcessorId \n" 
          + " exit for ' do the first cpu only! \n" 
          + "Next \n"; 


      fw.write(vbs1); 
      fw.close(); 

      Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath()); 
      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); 
      String line; 
      while ((line = input.readLine()) != null) { 
       result += line; 
      } 
      input.close(); 
     } 
     catch(Exception E){ 
      System.err.println("Windows CPU Exp : "+E.getMessage()); 
     } 
     return result.trim(); 
    } 

這是從UUID:

private void getUUID(){ 
     String uniqueID = UUID.randomUUID().toString(); 
     System.out.println(uniqueID); 
    } 

從InetAddress類:

private void getMacFromInetAddress(){ 
    String mmm = "123"; 
    try { 
      InetAddress ip = InetAddress.getLocalHost(); 
      System.out.println("Current IP address : " + ip.getHostAddress()); 

      Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces(); 
      while (networks.hasMoreElements()) { 
       NetworkInterface network = networks.nextElement(); 
       byte[] mac = network.getHardwareAddress(); 

       if (mac != null) { 
        System.out.print("Current MAC address : "); 

        StringBuilder sb = new StringBuilder(); 
        for (int i = 0; i < mac.length; i++) { 
         sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); 
        } 
        mmm = sb.toString(); 
        System.out.println(mmm); 
       } 
      } 
     } catch (UnknownHostException | SocketException e) { 
      System.out.println(e.getLocalizedMessage()); 
     } 
} 

在從MB,硬盤,CPU的方法,InetAddress類如果我上運行多個相同參數的計算機代碼,它們將返回相同的代碼。從UUID運行代碼時,第一次返回其他代碼,第二次是其他代碼。如何在不改變Java的時間的情況下爲計算機獲取唯一的ID?我使用操作系統Windows。

回答

0

使用UUID有了一些變化

運行一日一次,生成一個唯一的UUID和在本地存儲保存。從第二次起使用第一次運行中保存的UUID。

+0

讓我們這樣說吧:我的每臺機器的程序只給出一個唯一的密鑰。如果我生成uuid並保存它的本地存儲,然後客戶端將複製這個程序與本地存儲,並把它放在另一臺機器,而不是本地密鑰.... – Saahon

1

如何從設備獲取MAC地址?

沒有直接的方法可以通過Java從系統獲得mac address。但是你可以

獲取計算機MAC地址,只要運行該命令getmac獲取MAC地址。 enter image description here

  1. 使用ipconfig命令來處理此問題。
  2. 使用nbtstat命令檢索遠程計算機的mac地址。
  3. 運行getmacgetmac /s remote_computer /u username /p password命令檢索遠程計算機的MAC地址。

Get mac address from command line

但通過的Java你需要使用Java exec system with Java ProcessBuilder and Process

例如:

ProcessBuilder pb = new ProcessBuilder("getmac"); 
//Map<String, String> env = pb.environment(); //set env 
pb.directory("C\\"); 
Process p = pb.start(); 

// build my command as a list of strings 
//@@@ For Unix/Linux 
List<String> command = new ArrayList<String>(); 
command.add("getmac"); 

// execute my command 
SystemCommandExecutor commandExecutor = new SystemCommandExecutor(command); 
int result = commandExecutor.executeCommand(); 

然後通過讀輸出:

// get the output from the command 
StringBuilder stdout = commandExecutor.getStandardOutputFromCommand(); 
StringBuilder stderr = commandExecutor.getStandardErrorFromCommand(); 

// print the output from the command 
System.out.println("STDOUT"); 
System.out.println(stdout); 
System.out.println("STDERR"); 
System.out.println(stderr); 

ProcessBuilder and Process Code

Note:java application需要administrative permission during execution

2
InetAddress ip = InetAddress.getLocalHost(); 
System.out.println("Current IP address : " + ip.getHostAddress()); 

NetworkInterface network = NetworkInterface.getByInetAddress(ip); 

byte[] mac = network.getHardwareAddress(); 

System.out.print("Current MAC address : "); 

StringBuilder sb = new StringBuilder(); 
for (int i = 0; i < mac.length; i++) { 
    sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); 
} 
System.out.println(sb.toString()); 

,並獲得硬件信息u可以使用像 WMIC CPU WMIC命令得到ProcessorId

Process p = Runtime.getRuntime().exec("wmic cpu get ProcessorId"); 
      String procesSerial= 
        new BufferedReader 
          (new InputStreamReader(p.getInputStream())).[ReadSecondLine]; 

和BIOS

WMIC BIOS得到的SerialNumber

Process p = Runtime.getRuntime().exec("wmic bios get SerialNumber"); 
+1

你甚至可以得到以太網適配器/ Mac地址列表if你需要 –

+0

朋友,這裏和mac地址虛擬網絡適配器也是,給出 然後將多臺機器上的mac地址相同 – Saahon

+0

@Saahon然後創建組合字符串,如 CPUID +「|」+ BIOSSerial +「|」+ MAC 這樣重複就會最小化。 如果你想讀取硬件信息,它不再是平臺獨立的。 謝謝。 –

0

我建議你看看oshi library來獲取系統操作系統/硬件信息。請參考test case

下面是我的系統上的截斷輸出。

Microsoft Windows 7 SP1 build 7601 
manufacturer: LENOVO 
model: 20AWA0MAIN 
serialnumber: PB01FEYL 
baseboard: 
    manufacturer: LENOVO 
    serialnumber: L1HF43B026Z    
Intel(R) Core(TM) i7-4600M CPU @ 2.90GHz 
2 physical CPU(s) 
4 logical CPU(s) 
Identifier: Intel64 Family 6 Model 60 Stepping 3 
ProcessorID: BFEBFBFF000306C3 
Memory: 9.2 GiB/15.7 GiB 
Swap used: 0 bytes/15.7 GiB 
Uptime: 0 days, 04:24:20 
Disks: 
\\.\PHYSICALDRIVE0: (model: HGST HTS725050A7E6300 SCSI Disk Device (Standard disk drives) - S/N:  TF655AWH2RKE6L) size: 500.1 GB, reads: 325475 (7.1 GiB), writes: 306825 (4.4 GiB), xfer: 12447064 ms 
|-- Disk #0, Partition #0: Installable File System (Installable File System) Maj:Min=0:0, size: 104.9 MB 
Network interfaces: 
Name: eth8 (Intel(R) Ethernet Connection I217-LM) 
    MAC Address: 28:d2:44:68:40:23 
    MTU: 1500, Speed: 0 bps 
    IPv4: [] 
    IPv6: [fe80:0:0:0:553d:8bc9:6a95:236e] 
    Traffic: received ?/?; transmitted ?/? 
Name: wlan9 (Intel(R) Dual Band Wireless-N 7260) 
    MAC Address: 7c:7a:91:37:cb:f7 
    MTU: 1500, Speed: 130 Mbps 
    IPv4: [192.168.1.66] 
    IPv6: [fe80:0:0:0:55e0:97b3:f282:4c06] 
    Traffic: received 121644 packets/114.0 MiB (0 err); transmitted 90086 packets/12.7 MiB (0 err) 
Displays: 
Display 0: 
    Manuf. ID=LEN, Product ID=40a0, Analog, Serial=00000000, ManufDate=1/2012, EDID v1.4 
    31 x 17 cm (12.2 x 6.7 in) 
    Preferred Timing: Clock 72MHz, Active Pixels 2656x768 
    Preferred Timing: Clock 63MHz, Active Pixels 2656x768 
    Manufacturer Data: 0000000F008C09328C093214090006AF3C33 
    Unspecified Text: B140XTN03.3