libpcap库的安装
首先,安装相关的支持环境
sudo apt get install flex
sudo apt get install bison
然后下载最新版的libpcap,下载地址:http://www.tcpdump.org/。
解压缩,在解压缩的文件夹输入以下命令
./configure
make
make install
单网卡抓包DEMO
单网卡抓包是libpcap库非常基础的功能,这里放出一个demo作为参考,方便与多网卡扩展做比较。
单网卡demo的主要功能是,由用户自行输入监听的网卡。在用户没有输入网卡时,程序会打印所有可监听的设备名称,由用户选择所要监听的网卡,当监听一定数量的网卡时(10000),程序终止。
//demo=single
#include "pcap.h"
#include "stdlib.h"
#include <time.h>
#include <arpa/inet.h>
#define SNAP_LEN 65536
//prototype of the packet handler
void dispatcher_handler(u_char *temp1,
const struct pcap_pkthdr *header, const u_char *pkt_data);
int main(int argc, char **argv)
{
char *dev = NULL; /* capture device name */
char errbuf[PCAP_ERRBUF_SIZE]; /* error buffer */
pcap_t *handle; /* packet capture handle */
pcap_if_t *alldev, *p;
char filter_exp[] = "tcp"; /* filter expression [3] */
struct bpf_program fp; /* compiled filter program (expression) */
bpf_u_int32 mask; /* subnet mask */
bpf_u_int32 net; /* ip */
int num_packets = 10000; /* number of packets to capture */
/* check for capture device name on command-line */
if (argc == 2) {
dev = argv[1];
}
else if (argc > 2) {
fprintf(stderr, "error: unrecognized command-line options\n\n");
exit(EXIT_FAILURE);
}
else {
/* find a capture device if not specified on command-line */
int i=0,num;
if(pcap_findalldevs(&alldev,errbuf)==-1)
{
printf("find all devices is error\n");
return 0;
}
for(p=alldev;p;p=p->next)
{
printf("%d:%s\n",++i,p->name);
if(p->description