wincap的使用总结

最近在做基于wincap的网络嗅探器,开始对wincap的嗅探过程有了了解

1.先获取当前主机上的所有网卡设备(如果之前对设备名了如指掌,那可以直接从 第二步 开始)

        if(pcap_findalldevs(&alldevs, errbuf) == -1)
        {
            fprintf(stderr,"Error in pcap_findalldevs_ex: %s\n", errbuf);
            exit(1);
        }
其中 alldevs 是个 pcap_if 结构体类型的指针,pcap_if结构体具体如下:
struct pcap_if {
	struct pcap_if *next;
	char *name;		/* name to hand to "pcap_open_live()" */
	char *description;	/* textual description of interface, or NULL */
	struct pcap_addr *addresses;
	bpf_u_int32 flags;	/* PCAP_IF_ interface flags */
};

2.从alldevs所指向的设备链表中找到想要监听的设备名也就是结构体中 pcap_if 中的name。然后使用下面这个

pcap_t* pcap_open_live (
const char * device,
int snaplen,
int promisc,
int to_ms,
char * ebuf) 
函数打开设备文件,其中返回值 pcap_t 是打开的抓取实例的描述符
        if ((fp = pcap_open_live(
	    d->name,//要抓取的网卡的设备名称
            65536,  //每次抓取包的长度	
            1,      //非0即为将网卡设置为混乱模式		
            1000,   //接收数据的等待时间					
            errbuf  //错误存放				
            )) == NULL)
        {
            fprintf(stderr,"\nError opening adapter\n");
            return -1;
        }
3.获取到了抓取实例的描述符之后,就可以使用函数pcap_next_ex来抓取数据包了
int pcap_next_ex (pcap_t *p,
struct pcap_pkthdr ** pkt_header,
const u_char ** pkt_data 
)
其中pkt_header 结构体为:
struct pcap_pkthdr {
	struct timeval ts;	//时间戳
	bpf_u_int32 caplen;	//在线抓包转到的长度
	bpf_u_int32 len;	//掉线时抓包的长度
};
其中pkt_data就是数据包,然后分析其中的数据就可以了

猜你喜欢

转载自blog.csdn.net/shihunyewu/article/details/70842481