views:

1679

answers:

2

What is the easiest way to get the network traffic sent and received bytes in objective c?

+2  A: 

It's not easy, and it's from C not Objective-C, but all the info you need is stored in the ifa_data field of the interface addresses returned to you by getifaddrs(3). You can see one example of how to access this in the source code to the 'top' utility, in the libtop_p_networks_sample function.

cdespinosa
+1  A: 

The cleaneast solution is probably cdespinosa's.

Alternates may be

1/ Wrapping a netstat call inside a NSTask

diciu$ netstat -bi en0
Name  Mtu   Network       Address            Ipkts Ierrs     Ibytes    Opkts Oerrs     Obytes  Coll
en0   1500  <Link#4>    xx:xx:xx:xx:xx    86259     0   86175096    64485     0   10090152     0

2/ Reading sysctl vars gets you some network statistics but these seem to not be tied to a particular interface:

diciu$ sysctl -b net.inet.ip.stats > /tmp/tt
diciu$ hexdump /tmp/tt
0000000 d2 4a 01 00 00 00 00 00 00 00 00 00 00 00 00 00
0000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

In the dump "d2 4a 01 00" is the total ip packets (i.e. 0x14ad2 = 84690 packets).

The structure you get is defined in netinet/ip_var.h:

struct  ipstat {
        u_int32_t       ips_total;              /* total packets received */
[..]
diciu