我已经搜索了这个主题,但发现很少有帮助的细节。有了这些细节,我试着编写一些代码,如下所示。
注意:在将本文标记为重复之前,请将此帖子中共享的详细信息与其他帖子进行比较,而不仅仅是按主题进行比较。
- (NSArray *)getDataCountersForType:(int)type {
BOOL success;
struct ifaddrs *addrs = nil;
const struct ifaddrs *cursor = nil;
const struct sockaddr_dl *dlAddr = nil;
const struct if_data *networkStatisc = nil;
int dataSent = 0;
int dataReceived = 0;
success = getifaddrs(&addrs) == 0;
if (success) {
cursor = addrs;
while (cursor != NULL) {
if (cursor->ifa_addr->sa_family == AF_LINK) {
dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
networkStatisc = (const struct if_data *) cursor->ifa_data;
if (type == WiFi) {
dataSent += networkStatisc->ifi_opackets;
dataReceived += networkStatisc->ifi_ipackets;
}
else if (type == WWAN) {
dataSent += networkStatisc->ifi_obytes;
dataReceived += networkStatisc->ifi_ibytes;
}
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
return [NSArray arrayWithObjects:[NSNumber numberWithInt:dataSent], [NSNumber numberWithInt:dataReceived], nil];
}
此代码收集iPhone设备(而不仅仅是我的应用程序)的互联网使用信息。
现在,如果我通过WiFi或3G使用互联网,我只能获得ifi_obytes
(发送)和ifi_ibytes
(接收)格式的数据(字节),但我认为我应该获得ifi_opackets
和ifi_ipackets
格式的WiFi使用情况。
我还想补充说,如果我连接到WiFi网络,但没有使用互联网,我仍然可以获得ifi_obytes
和ifi_ibytes
的附加值。
也许我在实现或理解上是错误的。需要有人来帮我。
编辑:我尝试了AF_INET
而不是AF_LINK
(sockaddr_in
而不是sockaddr_dl
)。这会使应用程序崩溃。
https://stackoverflow.com/questions/7946699
复制相似问题