github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/internal/machineid/id_windows.go (about) 1 //go:build windows 2 3 package machineid 4 5 import ( 6 "fmt" 7 "syscall" 8 "unsafe" 9 ) 10 11 func readPlatformMachineID() (string, error) { 12 // source: https://github.com/shirou/gopsutil/blob/master/host/host_syscall.go 13 var h syscall.Handle 14 err := syscall.RegOpenKeyEx(syscall.HKEY_LOCAL_MACHINE, syscall.StringToUTF16Ptr(`SOFTWARE\Microsoft\Cryptography`), 0, syscall.KEY_READ|syscall.KEY_WOW64_64KEY, &h) 15 if err != nil { 16 return "", err 17 } 18 defer syscall.RegCloseKey(h) 19 20 const syscallRegBufLen = 74 // len(`{`) + len(`abcdefgh-1234-456789012-123345456671` * 2) + len(`}`) // 2 == bytes/UTF16 21 const uuidLen = 36 22 23 var regBuf [syscallRegBufLen]uint16 24 bufLen := uint32(syscallRegBufLen) 25 var valType uint32 26 err = syscall.RegQueryValueEx(h, syscall.StringToUTF16Ptr(`MachineGuid`), nil, &valType, (*byte)(unsafe.Pointer(®Buf[0])), &bufLen) 27 if err != nil { 28 return "", err 29 } 30 31 hostID := syscall.UTF16ToString(regBuf[:]) 32 hostIDLen := len(hostID) 33 if hostIDLen != uuidLen { 34 return "", fmt.Errorf("HostID incorrect: %q\n", hostID) 35 } 36 37 return hostID, nil 38 }