-
Notifications
You must be signed in to change notification settings - Fork 0
/
mac.go
125 lines (118 loc) · 2.5 KB
/
mac.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package mklic
import (
"crypto/sha1"
"fmt"
"net"
"sort"
"strings"
)
func getMacs(macs string) ([]byte, int) {
if macs == "" {
// default use 2 interface macs, ethx/enxsx
macs = getNumEtherMacs(2)
}
nlen := len(macs)
if nlen < 17 || nlen%17 != 0 {
return nil, 0
}
num := len(macs) / 17
res := make([]byte, 0)
for i := 0; i < num; i++ {
tmp := macs[i*17 : (i+1)*17]
mac := make([]byte, 6)
fmt.Sscanf(tmp, "%02X:%02X:%02X:%02X:%02X:%02X", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5])
res = append(res, mac...)
}
return res, num
}
func macSha1(macs []byte, nmac int) []byte {
sha1output := make([]byte, 20)
for i := 0; i < nmac; i++ {
tmp := macs[i*6 : (i+1)*6]
h := sha1.New()
h.Write([]byte(tmp))
sha1one := h.Sum(nil)
for j := 0; j < 20; j++ {
sha1output[j] = sha1output[j] ^ sha1one[j]
}
}
return sha1output
}
func macBase32(s []byte) []byte {
b32set := "23456789WXYZABCDEFGHJKLMNPQRSTUV"
n := len(s)
if n%5 != 0 {
return nil
}
output := make([]byte, n/5*8)
i, j := 0, 0
for count := n; count >= 5; count -= 5 {
inpos := s[j*5 : j*5+5]
output[i] = b32set[inpos[0]>>3]
i++
output[i] = b32set[(inpos[4]&0x3E)>>1]
i++
output[i] = b32set[(inpos[1]&0x7C)>>2]
i++
output[i] = b32set[(inpos[3]&0x1F)>>3]
i++
output[i] = b32set[(inpos[0]&0x01)<<4|(inpos[4]&0xF0)>>4]
i++
output[i] = b32set[(inpos[1]&0x03)<<3|(inpos[3]&0xE0)>>5]
i++
output[i] = b32set[(inpos[2]&0x07)<<2|(inpos[2]&0xC0)>>6]
i++
output[i] = b32set[(inpos[3]&0x0F)<<1|(inpos[1]&0x80)>>7]
i++
j++
}
return output
}
func getNumEtherMacs(num int) string {
macs := ""
interfaces, err := net.Interfaces()
if err != nil {
return ""
}
eths := make([]string, 0)
ens := make([]string, 0)
ethinters := make(map[string]net.Interface)
eninters := make(map[string]net.Interface)
for _, i := range interfaces {
if strings.HasPrefix(i.Name, "eth") {
eths = append(eths, i.Name)
ethinters[i.Name] = i
} else if strings.HasPrefix(i.Name, "en") {
ens = append(ens, i.Name)
eninters[i.Name] = i
} else {
continue
}
}
if len(eths) == 0 && len(ens) == 0 {
return ""
}
var internames []string
var inters map[string]net.Interface
if len(eths) != 0 {
internames = eths
inters = ethinters
} else {
internames = ens
inters = eninters
}
sort.Strings(internames)
cnt := 0
for _, it := range internames {
macAddr := inters[it].HardwareAddr.String()
if len(macAddr) == 0 {
continue
}
macs += macAddr
cnt++
if cnt >= num {
break
}
}
return macs
}