【问题标题】:Get how many bytes received/sent by given process in OS X programatically?以编程方式获取 OS X 中给定进程接收/发送的字节数?
【发布时间】:2013-11-01 15:44:37
【问题描述】:

如何以编程方式获取 OS X 中给定进程接收和发送的字节数?

如何解决以下问题?

【问题讨论】:

  • 我的问题没有答案。我需要在 Obj C/C 中这样做。

标签: objective-c macos process kernel pid


【解决方案1】:

这并不容易,但它是可行的:通过在非常无证的“com.apple.network.statistics”上注册一个系统套接字(PF_SYSTEM),您可以获得每个进程的统计信息。问题是,它只是从注册点开始 - 即您不会知道在套接字启动之前有多少 rx/tx。

对此没有用户模式标头,但您可以使用该站点上的 lsock.h,或者从 xnu 自己的源 (q.v. xnu-2422.1.72/bsd/net/ntstat.h) 中提取定义。相关部分是:

,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

顺便说一句,从 10.9 开始,ActivityMonitor 在“网络”视图中也是这样做的,因此这几乎是唯一导出的编程 API。该站点中的“进程资源管理器”工具也以相同的方式提供每个进程的统计信息。

【讨论】:

    【解决方案2】:

    我调查了上述观点并开发/更新了执行此操作的工具:https://github.com/sotrosh/lsock

    【讨论】:

    • 这点并不重要,但不接受我的回答并接受你的回答是相当低俗的,因为你开发/更新的工具是我自己工具的直接翻版。为开源的力量喝彩。像你这样的人让我不想发布我的任何消息来源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多