2

在我的电脑上有 3G、Wifi 和 LAN 端口。我想构建一个 linux 软件,如果有网络流量显示绿色,没有网络流量显示红色。

TCPDUMP 可以提供实时统计信息,但会产生高 CPU 负载。因此我想知道我是否可以通过软件中断获得实时统计信息?只要有网络流量,就会产生软件中断。

提前致谢

4

1 回答 1

1

我不知道您是否将其称为软件中断,但您可以参考以下示例。(poll() 的第三个参数是以毫秒为单位的时间,在此之后网络被认为是不活动的。)

/* compile with -lpcap */
/* run as root         */

#include <stdio.h>
#include <sys/poll.h>
#include <pcap.h>

int main(int argc, char *argv[])
{
    int color = 0;
    struct pollfd ufd;
    struct pcap_pkthdr h;
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t *p = pcap_open_live(NULL, 0, 0, 0, errbuf);
    if (!p) return puts(errbuf), 1;

    ufd.fd = pcap_fileno(p);
    ufd.events = POLLIN;
    for (; ; )
        switch (poll(&ufd, 1, 100))
        {
        case -1:    perror("poll"); return 1;
        case  0:    if  (color) color = 0, puts("red"); break;
        default:    if (!color) color = 1, puts("green");
                    pcap_next(p, &h);
        }
}
于 2013-06-04T12:13:46.527 回答