iOS開發——即時監控網速

來源:互聯網
上載者:User

標籤:

  開發中用到擷取網速的地方,應該就兩種:

  1、下載速度,這種可以直接在接受資料的地方統計計算。這個就不講了。
  2、擷取手機網卡的資料,可以監控網卡的進出流量,下面就是。

#import "ViewController.h"

 

#include <ifaddrs.h>

#include <arpa/inet.h>

#include <net/if.h>

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

        

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(getInternetface) userInfo:nil repeats:YES];

    [timer fireDate];

}

 

- (void)getInternetface {

    long long hehe = [self getInterfaceBytes];

    

    NSLog(@"hehe:%lld",hehe);

}

 

/*擷取網路流量資訊*/

- (long long) getInterfaceBytes

{

    struct ifaddrs *ifa_list = 0, *ifa;

    if (getifaddrs(&ifa_list) == -1)

    {

        return 0;

    }

    

    uint32_t iBytes = 0;

    uint32_t oBytes = 0;

    

    for (ifa = ifa_list; ifa; ifa = ifa->ifa_next)

    {

        if (AF_LINK != ifa->ifa_addr->sa_family)

            continue;

        

        if (!(ifa->ifa_flags & IFF_UP) && !(ifa->ifa_flags & IFF_RUNNING))

            continue;

        

        if (ifa->ifa_data == 0)

            continue;

        

        /* Not a loopback device. */

        if (strncmp(ifa->ifa_name, "lo", 2))

        {

            struct if_data *if_data = (struct if_data *)ifa->ifa_data;

            

            iBytes += if_data->ifi_ibytes;

            oBytes += if_data->ifi_obytes;

        }

    }

    freeifaddrs(ifa_list);

    

    NSLog(@"\n[getInterfaceBytes-Total]%d,%d",iBytes,oBytes);

    return iBytes + oBytes;

}

@end

 

iOS開發——即時監控網速

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.