以编程方式告知OSX中使用哪个接口(wifi或线路)(活动)

时间:2015-05-25 16:52:58

标签: macos network-interface

SCNetworkReachability无法判断它是通过有线还是无线连接。另一种可能的方法是获取活动接口的名称,然后与从SCNetworkInterfaceGetBSDName获取的名称进行比较,然后使用SCNetworkInterfaceGetInterfaceType获取类型。这个问题是SCNetworkInterface *似乎不适用于VPN连接。

std::string bsdName = get_primary_bsdName();
if (bsdName.length() == 0)
    return NotDetected;

CFArrayRef interfaces;
CFIndex num_interfaces;
CFIndex i;
SCNetworkInterfaceRef interface;
CFStringRef name_CFString;
CFStringRef bsdname_CFString;
CFStringRef friendly_name_CFString;
CFStringRef interface_type_CFString;

interfaces = SCNetworkInterfaceCopyAll();
if (interfaces == NULL) {
    return NotDetected;
}

name_CFString = CFStringCreateWithCString(kCFAllocatorDefault,
    bsdName.c_str(), kCFStringEncodingUTF8);
if (name_CFString == NULL) {
    CFRelease(interfaces);
    return NotDetected;
}
eNetworkStatus retVal = NotDetected;

num_interfaces = CFArrayGetCount(interfaces);
for (i = 0; i < num_interfaces; i++) {
    interface = (SCNetworkInterfaceRef)CFArrayGetValueAtIndex(interfaces, i);
    CFShow(interface);
    bsdname_CFString = SCNetworkInterfaceGetBSDName(interface);
    if (bsdname_CFString == NULL) {
        continue;
    }
    if (CFStringCompare(name_CFString, bsdname_CFString, 0) == 0)
    {
        interface_type_CFString = SCNetworkInterfaceGetInterfaceType(interface);
        if (CFStringCompare(interface_type_CFString,
            kSCNetworkInterfaceTypeIEEE80211, 0) == kCFCompareEqualTo)
            retVal = ReachableViaWiFi;
        else if (CFStringCompare(interface_type_CFString,
            kSCNetworkInterfaceTypeBluetooth, 0) == kCFCompareEqualTo)
            retVal = ReachableViaBlueTooth;
        else if (CFStringCompare(interface_type_CFString,
            kSCNetworkInterfaceTypeModem, 0) == kCFCompareEqualTo)
            retVal = ReachableViaModem;
        else if (CFStringCompare(interface_type_CFString,
            kSCNetworkInterfaceTypePPP, 0) == kCFCompareEqualTo)
            retVal = ReachableViaPPP;
        else if (CFStringCompare(interface_type_CFString,
            kSCNetworkInterfaceTypeWWAN, 0) == kCFCompareEqualTo)
            retVal = ReachableViaWWAN;
        else
            retVal = ReachableViaWIRE;
    }
}

CFRelease(interfaces);
CFRelease(name_CFString);

0 个答案:

没有答案