pcap_close(fp); /* 释放设备列表 */ return; } printf("NetWork traffic summary:\n"); /* 开始主循环 */ pcap_loop(fp, 0, dispatcher_handler, (PUCHAR)&st_ts); pcap_close(fp); return; } void dispatcher_handler(u_char *state, const struct pcap_pkthdr *header, const u_char *pkt_data) { struct timeva l *old_ts = (struct timeva l *)state; u_int delay; LARGE_INTEGER Bps,Pps; struct tm *ltime; char timestr[16]; time_t local_tv_sec; /* 以毫秒计算上一次采样的延迟时间 */ /* 这个值通过采样到的时间戳获得 */ delay=(header->ts.tv_sec - old_ts->tv_sec) * 1000000 - old_ts->tv_usec + header->ts.tv_usec; /* 获取每秒的比特数b/s */ Bps.QuadPart=(((*(LONGLONG*)(pkt_data + 8)) * 8 * 1000000) / (delay)); /* ^ ^ | | | | | | 将字节转换成比特 -- | | 延时是以毫秒表示的 -- */ /* 得到每秒的数据包数量 */ Pps.QuadPart=(((*(LONGLONG*)(pkt_data)) * 1000000) / (delay)); /* 将时间戳转化为可识别的格式 */ local_tv_sec = header->ts.tv_sec; ltime=localtime(&local_tv_sec); strftime( timestr, sizeof timestr, "%H:%M:%S", ltime); /* 打印时间戳*/ printf("%s ", timestr); /* 打印采样结果 */ printf("BPS=%I64u ", Bps.QuadPart); printf("PPS=%I64u\n", Pps.QuadPart); //存储当前的时间戳 old_ts->tv_sec=header->ts.tv_sec; old_ts->tv_usec=header->ts.tv_usec; } void usage() { printf("\nShows the TCP traffic load, in bits per second and packets per second.\nCopyright (C) 2002 Loris Degioanni.\n"); printf("\nUsage:\n"); printf("\t tcptop adapter\n"); printf("\t You can use \"WinDump -D\" if you don't know the name of your adapters.\n"); exit(0); }
摘自 牧心_hp 学习人生
|