libpcap 安装和测试

 libpcap是一个与实现无关的访问操作系统所提供的分组捕获机制的分组捕获函数库,目前只支持分组的读取,当然增加一些代码之后,也可以写数据链路分组

I 首先安装 libpcap

     1.  下载并安装 GNU M4   , 为生成makefile使用

     2.  下载并安装 flex

     3.  下载并安装 bison

     4.  下载并安装libpcap。

II 测试libpcap是否好用:

 

C代码
  1. #include <stdio.h>   
  2. #include <pcap.h>   
  3.     
  4. int main(int argc, char *argv[]) {   
  5.         char errbuf[PCAP_ERRBUF_SIZE];   
  6.         pcap_if_t* devs;   
  7.         pcap_if_t* d;   
  8.         unsigned int i = 0;   
  9.                         
  10.         //获取全部的dev   
  11.         if (-1 == pcap_findalldevs(&devs, errbuf)) {   
  12.             fprintf(stderr, "Could not list device: %s\n", errbuf);   
  13.         } else {   
  14.             d = devs;   
  15.             while (d->next != NULL) {   
  16.                 printf("%d:%s\n", i++, d->name);   
  17.                 d = d->next;   
  18.             }   
  19.        }   
  20.                                                                      
  21.       //释放所有获取的dev   
  22.       pcap_freealldevs(devs);   
  23.       return (0);   
  24. }  
#include <stdio.h>
#include <pcap.h>
 
int main(int argc, char *argv[]) {
        char errbuf[PCAP_ERRBUF_SIZE];
        pcap_if_t* devs;
        pcap_if_t* d;
        unsigned int i = 0;
                     
        //获取全部的dev
        if (-1 == pcap_findalldevs(&devs, errbuf)) {
            fprintf(stderr, "Could not list device: %s\n", errbuf);
        } else {
            d = devs;
            while (d->next != NULL) {
                printf("%d:%s\n", i++, d->name);
                d = d->next;
            }
       }
                                                                  
      //释放所有获取的dev
      pcap_freealldevs(devs);
      return (0);
}
 

编译命令:

gcc test.c -lpcap  
gcc test.c -lpcap

 一定要加上 -lpcap, 链接库,否则无法正确链接。还有,如果是ubuntu,运行./a.out时还需要管理员权限,你懂的。

    sudo ./aout