我正在使用Reachability框架来检测接口类型。使用单一界面时,它工作正常。但是当使用多个网络接口时,它会异常工作。它在以下情况下失败 -
假设您有两个网络接口,一个是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。有人可以告诉我如何正确确定所有网络接口的类型。
N.B:我在C ++库解决方案中使用上述代码,这是一个跨平台库。
答案 0 :(得分:0)
此问题已得到修复。发布以便用户可以获得帮助。主要问题是我在zeroAddress结构中传递NULL。在结构中分配我的网络接口地址后,它会正确传递所有案例和确定的网络接口类型。