Sergio Sergio - 5 months ago 15
Objective-C Question

Get how many bytes received/sent by given process in OS X programatically?

How to get how many bytes received and sent by given process in OS X programatically?

How to resolve the following issue?

Answer

It's not easy, but it's doable: By registering a system socket (PF_SYSTEM) on the very undocumented "com.apple.network.statistics", you can get per process statistics. The hitch is, that it's only from the point of registration - i.e. you won't know how much rx/tx there was before the socket was started.

There's no user mode header for this, but you can either use the lsock.h on that site, or rip the definition from xnu's own sources (q.v. xnu-2422.1.72/bsd/net/ntstat.h). The relevant portion is:

,NSTAT_MSG_TYPE_SRC_COUNTS              = 10004
    typedef struct nstat_counts
    {
            /* Counters */
            u_int64_t       nstat_rxpackets __attribute__((aligned(8)));
            u_int64_t       nstat_rxbytes   __attribute__((aligned(8)));
            u_int64_t       nstat_txpackets __attribute__((aligned(8)));
            u_int64_t       nstat_txbytes   __attribute__((aligned(8)));

            u_int32_t       nstat_rxduplicatebytes;
            u_int32_t       nstat_rxoutoforderbytes;
            u_int32_t       nstat_txretransmit;

            u_int32_t       nstat_connectattempts;
            u_int32_t       nstat_connectsuccesses;

            u_int32_t       nstat_min_rtt;
            u_int32_t       nstat_avg_rtt;
            u_int32_t       nstat_var_rtt;
    } nstat_counts;

typedef struct nstat_msg_src_counts
{
        nstat_msg_hdr           hdr;
        nstat_src_ref_t         srcref;
        nstat_counts            counts;
} nstat_msg_src_counts

This, incidentally, is also how ActivityMonitor does so as of 10.9 in the "Network" view, so that's pretty much the only programmatic API exported. The "process explorer" tool in that site also provides per-process statistics in the same way.

Comments