I'm trying to determine if the current active/default network is wifi or ethernet in a reasonable reliable way. Windows offers a command netsh.exe interface ipv4 show interfaces
This seems to be reliable except I don't really like shelling out to the CLI for this sort of thing. At least things are reasonable in Windows. The OSX analog is far less reliable or accurate. Using the net.Interface
is not reliable as FlagUp
is also ambiguous. My next test might be to check for FlagBooadcast
per this
Clearly the answer varies based on the OS. This question was specific to OSX. The biggest challenge is that it is possible, but unusual, to have two active and route-able devices on a personal computer that is not bridging networks. That's more of a server function... In my case I'm interested in the ONE network media device. And that can be complicated...
On OSX there is an OS tool that dumps the device types in priority order with their accompanying device name.
networksetup -listnetworkserviceorder
I had to capture the output then parse it in order to call the following isactive
function.
func isactive(name string) bool {
if iface, err := net.InterfaceByName(name); err!=nil {
log.Printf("could not locate %s interface - %v", name, err)
} else {
if addrs, err := iface.Addrs(); err!=nil || len(addrs)==0 {
log.Printf("could not locate %s addr - %v", name, err)
return false
}
if iface.Flags & net.FlagBroadcast == net.FlagBroadcast && iface.Flags & net.FlagUp == net.FlagUp {
//log.Printf("%s is active", name)
return true
}
}
return false
}
In retrospect there is one other thing to note... iface.Addrs()
could return more than one IP address. But again unlikely in the normal use-case.