2018-09-20 16:43:31 +02:00
|
|
|
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
|
|
|
|
}
|
2018-09-20 17:34:34 +02:00
|
|
|
result = append(result, ifaces...)
|
2018-09-20 16:43:31 +02:00
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
// ListWirelessInterfaces list all wifi cards
|
2018-09-21 14:36:06 +02:00
|
|
|
// you need to provide the wireless file or "" to use
|
|
|
|
// Linux default one "/proc/net/wireless"
|
|
|
|
func (n *Network) ListWirelessInterfaces(wifiFile string) []net.Interface {
|
2018-09-20 16:43:31 +02:00
|
|
|
var result []net.Interface
|
|
|
|
var ifaceNames []string
|
|
|
|
|
2018-09-21 14:36:06 +02:00
|
|
|
if wifiFile == "" {
|
|
|
|
wifiFile = "/proc/net/wireless"
|
|
|
|
}
|
2018-09-20 16:43:31 +02:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|