程序1, 获取网卡信息并启动capture
func.h
#pragma once #ifndef __FUNC_H #define __FUNC_H #define HAVE_REMOTE #include<winsock2.h> #include<windows.h> #include<stdio.h> #include"pcap.h" #include"remote-ext.h" //获取网卡信息 void showNetworkAdapter(); //获取网卡属性 void showAdapterInfo(); //捕获数据包 void capturePackets(); //输出捕获的数据包的回调函数 void showCapturedData(u_char* param, const struct pcap_pkthdr* header, const u_char* pkt_data); #endif // !__FUNC_H
func.cpp
#include"func.h" void showNetworkAdapter() { pcap_if_t* pAdapter; pcap_if_t* temp; char errorBuffer[1024] = { 0 }; if (pcap_findalldevs_ex("rpcap://", 0, &pAdapter, errorBuffer) == -1) { fprintf(stderr, "获取网卡信息失败,原因:%s ", errorBuffer); return; } if (pAdapter==NULL) { printf("没有网卡 "); return; } temp = pAdapter; while (temp) { printf("网卡名: %s 网卡信息: %s ", temp->name, temp->description); temp = temp->next; } pcap_freealldevs(pAdapter); } void showAdapterInfo() { } void capturePackets() { pcap_if_t* pAdapter; pcap_if_t* temp; pcap_t* ptargetAdapter; size_t no = 0; size_t target_no = 0; char errorBuffer[1024] = { 0 }; if (pcap_findalldevs_ex("rpcap://", 0, &pAdapter, errorBuffer) == -1) { fprintf(stderr, "获取网卡信息失败,原因:%s ", errorBuffer); return; } if (pAdapter == NULL) { printf("没有网卡 "); return; } temp = pAdapter; while (temp) { no++; printf("No %d:网卡名: %s 网卡信息: %s ", no, temp->name, temp->description); temp = temp->next; } printf("输入要捕获的网卡号:1-%d ", no); scanf("%d", &target_no); temp = pAdapter; for (size_t i = 1; i < target_no; i++) { temp = temp->next; } //以混杂模式打开目标设备并设置捕获数据每次捕获时间间隔为1s. memset(errorBuffer, 0, sizeof(errorBuffer)); ptargetAdapter = pcap_open(temp->name, 1024, PCAP_OPENFLAG_PROMISCUOUS, 1000, 0, errorBuffer); if (ptargetAdapter==0) { fprintf(stderr, "打开失败,错误原因:%s ",errorBuffer); } printf("在设备%s启动监听... ", temp->description); pcap_freealldevs(pAdapter); //设置回调函数并捕获数据包给回调函数处理.数据包作为参数自动发给回调函数.还能能回调函数发送 //一个自定义参数,这里没有,直接设置为0 pcap_loop(ptargetAdapter, 0, showCapturedData, 0); } //捕获数据包回调函数,第一个参数是pcap_loop函数给的,第2个参数是数据包包头信息是由winpcap封装的 //结构体. 第3个参数是数据包内容 void showCapturedData(u_char * param, const pcap_pkthdr * header, const u_char * pkt_data) { //下面几行是处理数据包头的发送时间戳转为正常时间,代码固定 struct tm* ltime; char timestr[16] = { 0 }; time_t local_tv_sec = header->ts.tv_sec; ltime = localtime(&local_tv_sec); strftime(timestr, sizeof(timestr), "%H:%M:%S", ltime); printf("%s,%.6d len:%d ", timestr, header->ts.tv_usec, header->len); }
main.cpp
#include "func.h" int main() { WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); //showNetworkAdapter(); capturePackets(); return 0; }