dongpu9481 2017-12-08 17:54
浏览 313

如何确定活动的网络接口媒体类型?

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

  • 写回答

1条回答 默认 最新

  • douchenbiao0916 2017-12-23 16:46
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行