我的程序从互联网捕获网络流量以分析数据包的歧义。我正在使用 winPcap 库。现在我希望程序运行 2 分钟并自动退出程序,而无需手动关闭命令提示符控制台。你能提供我这样做的代码吗?谢谢你
代码如下:
int main()
{
u_int i, res , inum ;
u_char errbuf[PCAP_ERRBUF_SIZE] , buffer[100];
u_char *pkt_data;
time_t seconds;
struct tm tbreak;
pcap_if_t *alldevs, *d;
pcap_t *fp;
struct pcap_pkthdr *header;
fopen_s(&logfile , "log.txt" , "w");
if(logfile == NULL)
{
printf("Unable to create file.");
}
/* The user didn't provide a packet source: Retrieve the local device list */
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs_ex: %s\n", errbuf);
return -1;
}
i = 0;
/* Print the list */
for(d=alldevs; d; d=d->next)
{
printf("%d. %s\n ", ++i, d->name);
if (d->description)
{
printf(" (%s)\n", d->description);
}
else
{
printf(" (No description available)\n");
}
}
if (i==0)
{
fprintf(stderr,"No interfaces found! Exiting.\n");
return -1;
}
printf("Enter the interface number you would like to sniff : ");
scanf_s("%d" , &inum);
/* Jump to the selected adapter */
for (d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the device */
if ( (fp= pcap_open(d->name,
100 /*snaplen*/,
PCAP_OPENFLAG_PROMISCUOUS /*flags*/,
20 /*read timeout*/,
NULL /* remote authentication */,
errbuf)
) == NULL)
{
fprintf(stderr,"\nError opening adapter\n");
return -1;
}
//read packets in a loop :)
while((res = pcap_next_ex( fp, &header, &pkt_data)) >= 0)
{
if(res == 0)
{
// Timeout elapsed
continue;
}
seconds = header->ts.tv_sec;
localtime_s( &tbreak , &seconds);
strftime (buffer , 80 , "%d-%b-%Y %I:%M:%S %p" , &tbreak );
//print pkt timestamp and pkt len
//fprintf(logfile , "\nNext Packet : %ld:%ld (Packet Length : %ld bytes) " , header->ts.tv_sec, header->ts.tv_usec, header->len);
fprintf(logfile , "\nNext Packet : %s.%ld (Packet Length : %ld bytes) " , buffer , header->ts.tv_usec, header->len);
ProcessPacket(pkt_data , header->caplen);
}
if(res == -1)
{
fprintf(stderr, "Error reading the packets: %s\n" , pcap_geterr(fp) );
return -1;
}
return 0;
}