forked from jaypipes/ghw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnet_linux.go
More file actions
78 lines (66 loc) · 1.58 KB
/
net_linux.go
File metadata and controls
78 lines (66 loc) · 1.58 KB
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
// Use and distribution licensed under the Apache license version 2.
//
// See the COPYING file in the root project directory for full text.
//
package ghw
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
)
const (
PathSysClassNet = "/sys/class/net"
)
func netFillInfo(info *NetworkInfo) error {
info.NICs = NICs()
return nil
}
func NICs() []*NIC {
nics := make([]*NIC, 0)
files, err := ioutil.ReadDir(PathSysClassNet)
if err != nil {
return nics
}
for _, file := range files {
filename := file.Name()
// Ignore loopback...
if filename == "lo" {
continue
}
netPath := filepath.Join(PathSysClassNet, filename)
dest, _ := os.Readlink(netPath)
isVirtual := false
if strings.Contains(dest, "virtio") {
isVirtual = true
}
nic := &NIC{
Name: filename,
IsVirtual: isVirtual,
}
mac := netDeviceMacAddress(filename)
nic.MacAddress = mac
nics = append(nics, nic)
}
return nics
}
func netDeviceMacAddress(dev string) string {
// Instead of use udevadm, we can get the device's MAC address by examing
// the /sys/class/net/$DEVICE/address file in sysfs. However, for devices
// that have addr_assign_type != 0, return None since the MAC address is
// random.
aatPath := filepath.Join(PathSysClassNet, dev, "addr_assign_type")
contents, err := ioutil.ReadFile(aatPath)
if err != nil {
return ""
}
if strings.TrimSpace(string(contents)) != "0" {
return ""
}
addrPath := filepath.Join(PathSysClassNet, dev, "address")
contents, err = ioutil.ReadFile(addrPath)
if err != nil {
return ""
}
return strings.TrimSpace(string(contents))
}