This repository has been archived on 2024-08-02. You can view files and clone it, but cannot push or open issues or pull requests.
orion/openwrt/network.go
Philippe Caseiro b34ccd3dee Improving network_test.go ...
This way we don't need a real wifi card
2018-09-21 14:36:06 +02:00

78 lines
1.7 KiB
Go

package openwrt
import (
"fmt"
"io/ioutil"
"net"
"strings"
)
// Network provides a representation of network
type Network struct {
exec Executor
}
// NewNetwork return an UCI instance to interact with UCI
func NewNetwork() *Network {
exec := &localExecutor{}
return &Network{exec}
}
// NewNetworkWithExecutor return an UCI instance to interact with UCI
func NewNetworkWithExecutor(exe Executor) *Network {
exec := exe
return &Network{exec}
}
// ListInterfaces list all available interfaces on a system using "ip" commmand
func (n *Network) ListInterfaces() []net.Interface {
var result []net.Interface
ifaces, err := net.Interfaces()
if err != nil {
fmt.Print(fmt.Errorf("error listing network interfacess: %+v", err.Error()))
return nil
}
result = append(result, ifaces...)
return result
}
// ListWirelessInterfaces list all wifi cards
// you need to provide the wireless file or "" to use
// Linux default one "/proc/net/wireless"
func (n *Network) ListWirelessInterfaces(wifiFile string) []net.Interface {
var result []net.Interface
var ifaceNames []string
if wifiFile == "" {
wifiFile = "/proc/net/wireless"
}
wifiFileContent, err := ioutil.ReadFile(wifiFile)
check(err)
index := 0
for _, line := range strings.Split(string(wifiFileContent), "\n") {
if index < 2 {
index++
continue
} else {
name := strings.Split(line, ":")[0]
ifaceNames = append(ifaceNames, name)
}
}
ifaces, err := net.Interfaces()
if err != nil {
fmt.Print(fmt.Errorf("error listing network interfaces : %+v", err.Error()))
return nil
}
for _, i := range ifaces {
for _, name := range ifaceNames {
if name == i.Name {
result = append(result, i)
}
}
}
return result
}