目前用的1.3.0的版本以为很新了,没想到官方都已经1.6.2了
1012 wget http://www.tcpdump.org/release/libpcap-1.6.2.tar.gz
1013 tar zxvf libpcap-1.6.2.tar.gz
1014 cd libpcap-1.6.2
1015 ./configure
1016 make
1017 sudo make install
安装之后,动态库和静态库都会安装到/usr/local/lib下:
[lihui@master]$ ll /usr/local/lib/libpcap.*
-rw-r–r—. 1 root root 1385886 Dec 27 21:57 /usr/local/lib/libpcap.a
lrwxrwxrwx. 1 root root 12 Dec 27 21:57 /usr/local/lib/libpcap.so -> libpcap.so.1
lrwxrwxrwx. 1 root root 16 Dec 27 21:57 /usr/local/lib/libpcap.so.1 -> libpcap.so.1.6.2
-rwxr-xr-x. 1 root root 849206 Dec 27 21:57 /usr/local/lib/libpcap.so.1.6.2
头文件会安装到/usr/local/include下:
[lihui@master]$ ll /usr/local/include/pcap*.h
-rw-r–r–. 1 root root 2295 Dec 27 21:57 /usr/local/include/pcap-bpf.h
-rw-r–r–. 1 root root 2226 Dec 27 21:57 /usr/local/include/pcap.h
-rw-r–r–. 1 root root 2024 Dec 27 21:57 /usr/local/include/pcap-namedb.h
假如需要监听某个网口,可以自己手动指定配置,也可以通过库函数自己获取,用到的函数是char *pcap_lookupdev (char *ebuf)
关于函数返回,作者的解释:* Return the name of the 1st network interface, or NULL if none can be found.也就是说返回第一个网口,更确切的说是返回第一个可以用的网口,如果出错,那么字符串ebuf就用来存放出错信息,至于长度,一般用宏PCAP_ERRBUF_SIZE来表示,他是在pcap.h里定义的:#define PCAP_ERRBUF_SIZE 256
如此一来,可以这么写:
[lihui@master work]$ cat devices.c
#include <stdio.h>
#include <pcap.h>
int main(){
char ebuf[PCAP_ERRBUF_SIZE];
char *device;
device = pcap_lookupdev(ebuf);
if (device)
printf(“Now: %s is found!\n”, device);
else
printf(“Error: %s\n”, ebuf);
return 0;
}
这里由于libpcap已经被我们安装到系统目录下了,因而直接这样include就行了,下面就是编译和运行:
[lihui@master work]$ gcc devices.c -lpcap
[lihui@master work]$ ./a.out
Now: eth0 is found!
第一步,打完收工!