hostid_windows.go 1.0 KB

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