【发布时间】:2010-10-14 19:06:43
【问题描述】:
我的场景,我正在收集网络数据包,如果数据包与网络过滤器匹配,我想记录连续数据包之间的时间差,最后一部分是不起作用的部分。我的问题是,无论我使用什么 C 计时器功能,我都无法获得准确的亚秒级测量结果。我尝试过:gettimeofday()、clock_gettime() 和 clock()。
我正在寻求帮助以找出我的计时代码无法正常工作的原因。
我在 cygwin 环境中运行。 编译选项:gcc -Wall capture.c -o capture -lwpcap -lrt
代码 sn-p:
/*globals*/
int first_time = 0;
struct timespec start, end;
double sec_diff = 0;
main() {
pcap_t *adhandle;
const struct pcap_pkthdr header;
const u_char *packet;
int sockfd = socket(PF_INET, SOCK_STREAM, 0);
.... (previous I create socket/connect - works fine)
save_attr = tty_set_raw();
while (1) {
packet = pcap_next(adhandle, &header); // Receive a packet? Process it
if (packet != NULL) {
got_packet(&header, packet, adhandle);
}
if (linux_kbhit()) { // User types message to channel
kb_char = linux_getch(); // Get user-supplied character
if (kb_char == 0x03) // Stop loop (exit channel) if user hits Ctrl+C
break;
}
}
tty_restore(save_attr);
close(sockfd);
pcap_close(adhandle);
printf("\nCapture complete.\n");
}
在 got_packet 中:
got_packet(const struct pcap_pkthdr *header, const u_char *packet, pcap_t * p){ ... {
....do some packet filtering to only handle my packets, set match = 1
if (match == 1) {
if (first_time == 0) {
clock_gettime( CLOCK_MONOTONIC, &start );
first_time++;
}
else {
clock_gettime( CLOCK_MONOTONIC, &end );
sec_diff = (end.tv_sec - start.tv_sec) + ((end.tv_nsec - start.tv_nsec)/1000000000.0); // Packet difference in seconds
printf("sec_diff: %ld,\tstart_nsec: %ld,\tend_nsec: %ld\n", (end.tv_sec - start.tv_sec), start.tv_nsec, end.tv_nsec);
printf("sec_diffcalc: %ld,\tstart_sec: %ld,\tend_sec: %ld\n", sec_diff, start.tv_sec, end.tv_sec);
start = end; // Set the current to the start for next match
}
}
}
我用 Wireshark 记录所有数据包以进行比较,所以我希望我的计时器的差异与 Wireshark 的相同,但事实并非如此。我的 tv_sec 输出是正确的,但是 tv_nsec 甚至还没有接近。假设wireshark有0.5秒的差异,我的计时器会说有1.999989728秒的差异。
【问题讨论】:
标签: c sockets network-programming timer