libpcap库多网卡抓包

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值