日期:2014-05-16  浏览次数:20798 次

Linux环境下libpcap库源代码分析
linux环境下libpcap 源代码分析

韩大卫@吉林师范大学


libpcap 源代码官方下载地址:
git clone https://github.com/the-tcpdump-group/libpcap.git

tcpdumpm源代码官方下载地址:
git clone git://bpf.tcpdump.org/tcpdump

tcpdump.c使用libpcap里的pcap_open_livepcap_loop 完成两个最关键的动作:获取捕获报文的接口,和捕获报文并将报文交给callback(关于tcpdump源代码的构架,请参考作者的tcpdump源代码分析)
 
现结合libpcap源代码分析pcap_open_livepcap_loop的实现机制,并进入linux内核,展示linux内核对这两个API的响应动作。

tcpdump.cpcap_open_live的使用是:

pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf); 

pcap_open_live定义如下:

pcap_t *pcap_open_live(const char *source, int snaplen, int promisc, int to_ms, char *errbuf)

source 	为指定的网络接口。
snaplen 	为最大报文长度。
Promisc 	是否将设备设置为混杂模式。
to_ms 	超时时间。
errbuf 	为错误信息描述字符。

返回值为cap_t类型的指针,pcap_t 定义是:

typedef struct pcap pcap_t;
struct pcap {
/*typedef int (*read_op_t)(pcap_t *, int cnt, pcap_handler, u_char *);
read_op为从网络接口读取报文的函数指针,待其得到赋值后,调用实现函数*/
    read_op_t read_op;
 
//从文件里读取报文的函数指针
    int (*next_packet_op)(pcap_t *, struct pcap_pkthdr *, u_char **);
//文件描述符,socket
    int fd;
    int selectable_fd;   
    int bufsize;    //read缓冲区大小
    u_char *buffer; //read缓冲区指针
    u_char *bp;
    int cc;
...
    int snapshot;
    int linktype;       /* Network linktype */
    int linktype_ext;      
    int tzoff;      /* timezone offset */
    int offset;     /* offset for proper alignment */
    int activated;      /* true if the capture is really started */
    int oldstyle;       /* if we're opening with pcap_open_live() */
    struct pcap_opt opt; 
    u_char *pkt;
...
   //激活函数,激活函数在得到调用后,会建立起与底层IPCsocket
    activate_op_t activate_op;
...
};

pcap_t *
pcap_open_live(const char *source, int snaplen, int promisc, int to_ms, char *errbuf){   
    pcap_t *p;
    int status;
   //创建捕获报文的接口句柄
    p = pcap_create(source, errbuf);

    if (p == NULL)
        return (NULL);
    //设置最大报文长度
    status = pcap_set_snaplen(p, snaplen);
    if (status < 0)
        goto fail;
	//将设备设为混杂模式
    status = pcap_set_promisc(p, promisc);
    if (status < 0)
        goto fail;
	//设置超时时间
    status = pcap_set_timeout(p, to_ms);
    if (status < 0)
        goto fail;
    p->oldstyle = 1;
	//pcap_avtivate调用pcap_tactivate_op, 建立起与底层IPC通道
    status = pcap_activate(p);

    if (status < 0)
        goto fail;
    return (p);
...
}

pcap_t *pcap_create(const char *source, char *errbuf){   
    size_t i;
    int is_theirs;
    pcap_t *p;

    if (source == NULL)
        source = "an