当存在多个网络接口时,可访问性框架在检测接口类型时无法正常工作
Posted
技术标签:
【中文标题】当存在多个网络接口时,可访问性框架在检测接口类型时无法正常工作【英文标题】:Reachability framework is not working fine while detecting interface type when there is multiple network interface 【发布时间】:2014-10-20 01:54:21 【问题描述】:我正在使用可达性框架来检测接口类型。使用单个接口时,它工作正常。但是当使用多个网络接口时,它工作异常。在以下情况下失败 -
假设您有两个网络接口,一个是 WiFi,另一个是蜂窝网络(3G、2G、EDGE 等)。当我尝试检测每个接口的接口类型时,它会为每种情况返回 WiFi。但在仅连接 WiFi 或 3G 接口时工作正常。我已经使用以下代码来检测接口类型 -
static struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
SCNetworkReachabilityFlags flags;
AFNetworkInterfaceType interfaceType = AF_NIC_TYPE_UNKNOWN;
bool reachable = true;
UserInfo info;
static SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
SCNetworkReachabilityContext context = 0, &info, NULL, NULL, NULL;
if (SCNetworkReachabilityGetFlags(reachability, &flags))
if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
// The target host is not reachable.
reachable = false;
if ((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect))
interfaceType = AF_NIC_TYPE_WIFI;
if ( true == reachable && (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
/*
If the target host is reachable and no connection is required then we'll assume (for now) that you're on Wi-Fi...
*/
interfaceType = AF_NIC_TYPE_WIFI;
if ( true == reachable && (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
/*
... and the connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs...
*/
if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
/*
... and no [user] intervention is needed...
*/
interfaceType = AF_NIC_TYPE_WIFI;
if ( true == reachable && (flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
/*
... but WWAN connections are OK if the calling application is using the CFNetwork APIs.
*/
interfaceType = AF_NIC_TYPE_CELLULAR;
调试后我看到它进入第二个块并检测到接口类型WiFi。谁能告诉我如何正确确定所有网络接口的类型。
注意:我在 C++ 库解决方案中使用上述代码,这是一个跨平台库。
【问题讨论】:
【参考方案1】:此问题已修复。发布它以便用户可以获得帮助。主要问题是我在 zeroAddress 结构中传递了 NULL。在结构中分配我的网络接口地址后,它通过了所有案例并正确确定了网络接口类型。
【讨论】:
以上是关于当存在多个网络接口时,可访问性框架在检测接口类型时无法正常工作的主要内容,如果未能解决你的问题,请参考以下文章