owrt/network.go

84 lines
1.8 KiB
Go

package owrt
import (
"fmt"
"io/ioutil"
"net"
"strings"
)
// Network provides a representation of network
type Network struct {
exec Executor
}
// NewNetwork return an Network instance to interact with OpenWRT Network components
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" command
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]
if name != "" {
// remove damened whitespaces
name = strings.Replace(name, " ", "", -1)
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 _, name := range ifaceNames {
for _, iface := range ifaces {
if name == iface.Name {
result = append(result, iface)
}
}
}
return result
}