11package main
22
33import (
4- "encoding/json"
54 "fmt"
6- "io/ioutil"
7- "os/exec"
8- "strings"
9- )
10-
11- type Node struct {
12- Class string `json:"class"`
13- Id string `json:"id"`
14- BusInfo string `json:"businfo"`
15- LogicalName string `json:"logicalname"`
16- Config struct {
17- Children []Node `json:"children"`
18- } `json:"configuration"`
19- }
205
21- type DeviceInfo struct {
22- PCIAddress string
23- NetworkInterface string
24- LinkState string // "UP", "DOWN"
25- }
6+ nd "github.com/tlehman/pcinetiface/pkg/netdevices"
7+ )
268
279func main () {
28- devices , err := getPCIDevices ()
10+ devices , err := nd . GetPCINetInterfaces ()
2911 if err != nil {
3012 fmt .Printf ("Error: %v\n " , err )
3113 return
@@ -40,56 +22,3 @@ func main() {
4022 )
4123 }
4224}
43-
44- func getPCIDevices () ([]DeviceInfo , error ) {
45- cmd := exec .Command ("lshw" , "-class" , "network" , "-json" )
46- out , err := cmd .Output ()
47-
48- if err != nil {
49- return nil , err
50- }
51-
52- var lshwData []Node
53- err = json .Unmarshal (out , & lshwData )
54- if err != nil {
55- return nil , err
56- }
57-
58- var devices []DeviceInfo
59- findPCIDevices (lshwData , & devices )
60- return devices , nil
61- }
62-
63- func findPCIDevices (nodes []Node , devices * []DeviceInfo ) {
64- for _ , node := range nodes {
65- if node .Class == "network" {
66- pciAddress := ""
67- networkInterface := ""
68- if strings .HasPrefix (node .BusInfo , "pci" ) {
69- pciAddress = strings .TrimPrefix (node .BusInfo , "pci:" )
70- networkInterface = node .LogicalName
71- linkState , err := getLinkState (networkInterface )
72-
73- if err != nil {
74- fmt .Printf ("error getting link state: %s\n " , err )
75- }
76- * devices = append (* devices , DeviceInfo {
77- PCIAddress : pciAddress ,
78- NetworkInterface : networkInterface ,
79- LinkState : linkState ,
80- })
81- }
82- }
83- }
84- }
85-
86- func getLinkState (networkInterface string ) (string , error ) {
87- linkStatePath := fmt .Sprintf ("/sys/class/net/%s/operstate" , networkInterface )
88- content , err := ioutil .ReadFile (linkStatePath )
89- if err != nil {
90- return "" , err
91- }
92-
93- linkState := strings .TrimSpace (string (content ))
94- return linkState , nil
95- }
0 commit comments