-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmachine_code.go
46 lines (42 loc) · 865 Bytes
/
machine_code.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package goid
import (
"crypto/sha256"
"encoding/binary"
"errors"
"net"
"os"
)
var netInterfaceAddrs = net.InterfaceAddrs
var osHostname = os.Hostname
func GetLocalIP() (ip string, err error) {
addrs, err := netInterfaceAddrs()
if err != nil {
return
}
for _, addr := range addrs {
if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
ip = ipNet.IP.String()
break
}
}
}
if ip == "" {
err = errors.New("no non-loopback IP address found")
}
return
}
func GenerateMachineCode(bits int8) (code int, err error) {
machineName, err := osHostname()
if err != nil {
return
}
ip, err := GetLocalIP()
if err != nil {
return
}
combinedString := machineName + "_" + ip
hash := sha256.Sum256([]byte(combinedString))
code = int(binary.BigEndian.Uint64(hash[:])) & int(1<<bits-1)
return
}