linux的ubuntu14.04下的libpcap怎么测试

如题所述

为了开发需要,我决定使用最新libpcap源码包安装。在Unix环境下安装libpcap库,需要
c编译器,flex,bison等,安装Ubuntu系统时,没有这些包。安装flex需要m4编译环境,否则会提示“GNU M4 is required”错误。

1.安装系统依赖包
sudo apt-get install gcc libc6-dev
sudo apt-get install m4
sudo apt-get install flex bison

2.下载libpcap源码并安装
从官网http://www.tcpdump.org/下载最新的libpcap版本
cd /usr/local/src
wget http://www.tcpdump.org/release/libpcap-1.5.3.tar.gz
tar zxvf libpcap-1.5.3.tar.gz
cd libpcap-1.5.3
./configure
make
sudo make install

3.安装开发需要用到的依赖库
sudo apt-get install libpcap-dev

4.测试libpcap的小程序,命名为pcap_demo.c,以检验环境是否配置正确
#include <pcap.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
pcap_t *handle;
/* Session handle */
char *dev; /* The device to sniff on */
char errbuf[PCAP_ERRBUF_SIZE];
/* Error string */
struct bpf_program fp;
/* The compiled filter */
char filter_exp[] = "port 80";
/* The filter expression */
bpf_u_int32 mask;
/* Our netmask */
bpf_u_int32 net;
/* Our IP */
struct pcap_pkthdr header;
/* The header that pcap gives us */
const u_char *packet;
/* The actual packet */

/* Define the device */
dev = pcap_lookupdev(errbuf);
if (dev == NULL) {
fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
return(2);
}
/* Find the properties for the device */
if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
net = 0;
mask = 0;
}
/* Open the session in promiscuous mode */
handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
return(2);
}
/* Compile and apply the filter */
if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
return(2);
}
if (pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
return(2);
}
/* Grab a packet */
packet = pcap_next(handle, &header);
/* Print its length */
printf("Jacked a packet with length of [%d]\n", header.len);
/* And close the session */
pcap_close(handle);
return(0);
}
开始编译:
gcc -g pcap_demo.c -o pcap_demo -lpcap
开始执行
./pcap_demo

5.注意的问题
5.1.注意使用root用户来执行,或者对普通用户使用sudo来提升权限
sudo pcap_demo
5.2.对一些PCAP API函数要有全面地理解,并时刻更新文档,比如pcap_loop这个函数,下面是官网的man page地址
http://www.tcpdump.org/manpages/pcap.3pcap.html
温馨提示:答案为网友推荐,仅供参考