#define HAVE_REMOTE
#include "pcap.h"
int test()
{
pcap_if_t* alldevs;
pcap_if_t* d;
pcap_t* adhandle;
char errbuf[PCAP_ERRBUF_SIZE];
int inum;
int i = 0;
u_int netmask;
char packet_filter[] = "ip and tcp";
struct bpf_program fcode;
int res;
struct pcap_pkthdr* header;
struct tm* ltime;
const u_char* pkt_data;
time_t local_tv_sec;
char timestr[16];
ip_header* ih;
u_char* packet;
// 获得设备列表 pcap_findalldevs_ex()
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1) {
fprintf(stderr, "Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
for (d = alldevs; d; d = d->next) {
WriteLog(FormatString("%d. %s", ++i, d->name).c_str());
if (d->description) {
WriteLog(FormatString("(%s)\n", d->description).c_str());
}
else {
printf("No description available\n");
}
}
if (0 == i) {
printf("\nNo interface found!Make sure WinPcap is installed\n");
return -1;
}
//网卡,这里测试是我本机的,正常是需要选择的
for (d = alldevs, i = 1; i < 2; d = d->next, i++);
// 跳转到该设备,打开适配器
// 设备名,要捕捉的数据包的部分(65536保证能捕获到不同数据链路层上的每个数据包的全部内容),混杂模式,读取超时时间,错误缓冲池
if ((adhandle = pcap_open_live(d->name, 65536, 1, 1000, errbuf)) == NULL) {
fprintf(stderr, "\nUnable to open the adapter.%s is not supported by WinPcap\n", errbuf);
pcap_freealldevs(alldevs);
return -1;
}
// 检查数据链路层(只考虑了以太网)
if (pcap_datalink(adhandle) != DLT_EN10MB) {
fprintf(stderr, "\nThis program works only on Ethernet networks.\n");
pcap_freealldevs(alldevs);
return -1;
}
if (d->addresses != NULL) {
// 获得接口的第一个地址的掩码
netmask = ((struct sockaddr_in*)(d->addresses->netmask))->sin_addr.S_un.S_addr;
}
else {
netmask = 0xffffff;
}
// 编译过滤器
if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) < 0) {
fprintf(stderr, "\nUnable to compile the packet filter.Check the syntax\n");
pcap_freealldevs(alldevs);
return -1;
}
// 设置过滤器
if (pcap_setfilter(adhandle, &fcode) < 0) {
fprintf(stderr, "\nError setting the filter.\n");
pcap_freealldevs(alldevs);
return -1;
}
WriteLog(FormatString("\nlistenting on %s...\n", d->description).c_str());
pcap_dumper_t* dumpfp;
//输出文件 traffic.data
dumpfp = pcap_dump_open(adhandle, "traffic.data");
if (dumpfp == NULL) {
printf("Error on opening output file\n");
exit(-1);
}
while ((res = pcap_next_ex(adhandle, &header, &pkt_data)) >= 0) {
// 请求超时
if (0 == res) {
continue;
}
pcap_dump((u_char*)dumpfp, header, pkt_data);
}
pcap_dump_close(dumpfp);
pcap_freealldevs(alldevs);
return 0;
}
C++使用winpcap生成wireshark可解析文件
最新推荐文章于 2025-03-02 20:52:19 发布