102 lines
2.1 KiB
Go
102 lines
2.1 KiB
Go
package hardware
|
|
|
|
import (
|
|
"errors"
|
|
"net"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
var ignoredNetworks = []net.IPNet{
|
|
net.IPNet{IP: net.ParseIP("127.0.0.0"), Mask: net.IPv4Mask(255, 0, 0, 0)},
|
|
}
|
|
|
|
type NetworkDeviceInfo struct {
|
|
Name string
|
|
IP net.IP
|
|
Wireless bool
|
|
WirelessSSID string
|
|
WirelessLevel int // dBm
|
|
WirelessNoise int // dBm
|
|
}
|
|
|
|
func WiredNetworkInfo() (*NetworkDeviceInfo, error) {
|
|
ifaces, err := net.Interfaces()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
for _, iface := range ifaces {
|
|
log := logrus.WithField("interface", iface.Name)
|
|
ip := interfaceIP(iface)
|
|
if ip == nil {
|
|
log.Trace("interface has no IP address")
|
|
continue
|
|
}
|
|
if isWireless(iface) {
|
|
continue
|
|
}
|
|
return &NetworkDeviceInfo{
|
|
Name: iface.Name,
|
|
IP: ip,
|
|
}, nil
|
|
}
|
|
return nil, errors.New("hardware: no wired network interfaces found")
|
|
}
|
|
|
|
func WirelessNetworkInfo() (*NetworkDeviceInfo, error) {
|
|
ifaces, err := net.Interfaces()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
for _, iface := range ifaces {
|
|
log := logrus.WithField("interface", iface.Name)
|
|
ip := interfaceIP(iface)
|
|
if ip == nil {
|
|
log.Trace("interface has no IP address")
|
|
continue
|
|
}
|
|
if !isWireless(iface) {
|
|
continue
|
|
}
|
|
if ssid, level, noise, err := wirelessStatus(iface); err == nil {
|
|
return &NetworkDeviceInfo{
|
|
Name: iface.Name,
|
|
IP: ip,
|
|
Wireless: true,
|
|
WirelessSSID: ssid,
|
|
WirelessLevel: level,
|
|
WirelessNoise: noise,
|
|
}, nil
|
|
} else {
|
|
logrus.WithField("interface", iface.Name).WithError(err).Debug("wireless status failed")
|
|
}
|
|
}
|
|
return nil, errors.New("hardware: no wireless network interfaces found")
|
|
}
|
|
|
|
func interfaceIP(iface net.Interface) net.IP {
|
|
addrs, err := iface.Addrs()
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
address:
|
|
for _, addr := range addrs {
|
|
if ipnet, ok := addr.(*net.IPNet); ok {
|
|
if ipnet.IP.To4() == nil {
|
|
continue
|
|
}
|
|
for _, ignore := range ignoredNetworks {
|
|
if ignore.Contains(ipnet.IP) {
|
|
continue address
|
|
}
|
|
}
|
|
return ipnet.IP
|
|
} else {
|
|
logrus.Tracef("ignore addr type %T", addr)
|
|
}
|
|
}
|
|
return nil
|
|
}
|