libpcap是unix/linux平台下的网络数据包捕获函数库,大多数网络监控软件都以它为基础,Linux下著名的tcpdump就是以它为基础的。
Libpcap可以在绝大多数类unix平台下工作,Libpcap提供了系统独立的用户级别网络数据包捕获接口,并充分考虑到应用程序的可移植性。在windows平台下,一个与libpcap 很类似的函数包 winpcap 提供捕获功能。
使用libpcap读取tcpdump抓取的文件并解析c代码实例具体示例代码如下:
/*
* 发布网站: http://www.
*/
#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
//#define _DEBUG_
typedef struct pcap_pkthdr PCAP_PKTHEADER;
int printPktHeader(PCAP_PKTHEADER *pkt_Header);
int main(int argc, char *argv[])
{
if(argc<2)
{
fprintf(stdout,"please input test filenamen");
return 0;
}
fprintf (stdout, "test filename=%sn", argv[1]);
fprintf(stdout, "begin time=%dn", time(0));
//read the libpcap version
static char *version;
version = pcap_lib_version();
fprintf(stdout, "%sn", version);
//open the dumped cap file
char *dev, errBuff[PCAP_ERRBUF_SIZE];
pcap_t *handle = NULL;
handle = pcap_open_offline( argv[1] , errBuff);
if (NULL == handle) {
fprintf(stderr, "Error: %sn", errBuff);
return (EXIT_FAILURE);
}
#if defined(_DEBUG_)
fprintf(stdout,"running pcap_nextn");
#endif
//read the cap file , and print the every captured packet summary
PCAP_PKTHEADER *pktHeader;
int status;
u_char *pktData;
do {
#if defined(_DEBUG_)
fprintf(stdout, "status: %dn", status);
#endif
status = pcap_next_ex(handle, &pktHeader, &pktData );
// status = pcap_next(handle, &pktHeader );
printPktHeader(pktHeader);
} while (status == 1);
//close the handle
pcap_close(handle);
fprintf(stdout, "end time=%dn", time(0));
return (EXIT_SUCCESS);
}
int printPktHeader(PCAP_PKTHEADER *pktHeader)
{
#if defined(_DEBUG_)
fprintf(stdout,"running printPktHeadern");
#endif
fprintf(stdout, "cap_time:%u, ", (unsigned int)pktHeader->ts.tv_sec);
fprintf(stdout, "pkt length:%u, ", pktHeader->len);
fprintf(stdout, "cap length:%un", pktHeader->caplen);
}