java獲取硬碟ID以及MAC地址等唯一標識碼(詳解,測試通過)
阿新 • • 發佈:2019-01-08
為了達到軟體註冊,或者說軟體和電腦繫結的目的,需要將電腦上的固定編號進行一系列的演算法計算,並生成唯一和軟體匹配的號碼。
那麼使用java如何達到這個目的呢?
通常做法都是通過java的Runtime來完成,通過 process的輸入流,進行獲取相關的資訊。
下面列舉具體的例子:
1、DiskUtils 獲取硬碟編號
- import java.io.File;
- import java.io.FileWriter;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- class DiskUtils {
- private
- }
- publicstatic String getSerialNumber(String drive) {
- String result = "";
- try {
- File file = File.createTempFile("damn", ".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(\""
- + drive
- + "\")\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();
- }
- }
2、MacUtils 獲取MAC地址
- import java.io.InputStreamReader;
- import java.io.LineNumberReader;
- publicclass MacUtils {
- publicstaticvoid getMac(){
- try {
- Process process = Runtime.getRuntime().exec("ipconfig /all");
- InputStreamReader ir = new InputStreamReader(process.getInputStream());
- LineNumberReader input = new LineNumberReader(ir);
- String line;
- while ((line = input.readLine()) != null)
- if (line.indexOf("Physical Address") > 0) {
- String MACAddr = line.substring(line.indexOf("-") - 2);
- System.out.println("MAC address = [" + MACAddr + "]");
- }
- } catch (java.io.IOException e) {
- System.err.println("IOException " + e.getMessage());
- }
- }
- }
3、 測試程式:
- import java.io.InputStreamReader;
- import java.io.LineNumberReader;
- import java.net.NetworkInterface;
- import java.net.SocketException;
- import java.util.Enumeration;
- import java.util.Vector;
- publicclass TestMain {
- publicstaticvoid main(String[] args) {
- // TODO Auto-generated method stub
- //
- System.out.println("***MAC地址***");
- MacUtils.getMac();
- //
- String sn = DiskUtils.getSerialNumber("C");
- System.out.println("***硬碟編號***");
- System.out.println(sn);
- }
- }
4、執行結果(我電腦上有幾個VPN,所以就有多個MAC;為了防止別人搞我的電腦,數字和字母用*號代替)
***MAC地址***
MAC address = [**-**-**-**-**-**]
MAC address = [**-**-**-**-**-**]
MAC address =[**-**-**-**-**-**]
MAC address = [**-**-**-**-**-**]
***硬碟編號***
1290******