获得设备列表 pcap_findalldevs_ex,然后从设备列表中跳转到某个设备,并带开适配器。
调用pcap_datalink是为了减少数据包的数量:过滤掉不属于以太网的包。之后再设置过滤器,这里只是为了抓取 ip 和 tcp 的包
char packet_filter[] = "ip and tcp";
由于使用回调函数是由数据包捕获驱动直接控制,所以用户程序是无法直接控制的。这里我没有采用回调函数,而是使用的pcap_next_ex
#include <stdio.h>
#include <iostream>
#define HAVE_REMOTE
#include "pcap.h"
#include "remote-ext.h"
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "wpcap.lib")
using namespace std;
// 用户保存4字节的IP地址
typedef struct ip_address {
u_char byte1;
u_char byte2;
u_char byte3;
u_char byte4;
}ip_address;
// 用于保存IPV4的首部
typedef struct ip_header {
u_char ver_ihl;
u_char tos;
u_short tlen;
u_short identification;
u_short flags_fo;
u_char ttl;
u_char proto;
u_short crc;
ip_address saddr;
ip_address daddr;
u_int op_pad;
}ip_header;
// 保存UDP首部
type