libpcap学习(二) 网络数据抓取

1.netsniff.c

#include "netsniff.h"
#include <pcap.h>
void main ()
{
	//获取打印所有网卡信息
	//printf("Hi Hi~~~~\n");
	findDevsTables();
	freeDevsTables();
	//printf("hi, shabi!~");
//	start_catch();	
	pthread_create(&g_pthreadStartCatch, NULL, start_catch, NULL);		//网络数据抓取线程
	while(1)
	{
		sleep(50);
	}
}

void findDevsTables()
{
	char errbuf[PCAP_ERRBUF_SIZE];
	char *net;
	char *mask;
	int i = 0;
	pcap_if_t *d = NULL;
  	bpf_u_int32 netp; /* ip */
 	bpf_u_int32 maskp;/* subnet mask */
  	struct in_addr addr;

    	if (pcap_findalldevs(&g_tbNetCardInfo, errbuf) == -1)//返回网卡列表,alldevs指向表头
    	{
        	fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
        	return;
    	}
	for(d = g_tbNetCardInfo; d; d = d->next)
	{
		printf("%d. %s", ++i, d->name);
		if (d->description)
		{
			printf(" (%s)\n", d->description);
		}
		else 
			printf(" (No description available)\n");

		
		int ret = -1;
		ret = pcap_lookupnet(d->name, &netp, &maskp, errbuf);
		if(ret == -1)
		{
			printf ("lookupnet error : %s\n", errbuf);	
		}
		else
		{
  			addr.s_addr = netp;
	  		net = inet_ntoa(addr);
			printf("net : %s\n", net);
			addr.s_addr = maskp;
			mask = inet_ntoa(addr);
			printf("mask : %s\n", mask);
		}
	}

    	if(i==0)
    	{
       		printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
       		return;
    	}
	

}

void freeDevsTables()
{
	pcap_freealldevs(g_tbNetCardInfo);
}

//网络数据抓取后的回调函数,此处我们不对数据进行分析,简单的打印数据
void my_callback(u_char *useless,const struct pcap_pkthdr* pkthdr,const u_char*  packet)
{
	static int iCount = 1;
	printf("count is : %d\n ", iCount);
	iCount++;
}


/*
*网络数据抓取分为两步
*1.pcap_open_live
*2.调用pcap_loop 、pcap_dispatch函数,之后便可在回调函数中进行数据包分析
*/
void *start_catch(void *arg)
{
	
	char errbuf[PCAP_ERRBUF_SIZE];
	pcap_t *descr;
	
	//此处ETH1 可由pcap_findalldevs 函数得到
	descr = pcap_open_live("eth1", SNAPLEN, 0, READ_TIMEOUT, errbuf);
	if(descr == NULL)
    { 
		printf("pcap_open_live(): %s\n",errbuf); 
		exit(1); 
	}
	while(1)
	{
		//pcap_loop , pcap_dispatch 二选一即可
		//pcap_loop(descr, -1 ,my_callback,NULL);		
		pcap_dispatch(descr, -1, my_callback, NULL);			//网络数据抓取后的回调函数
		
		usleep(1000);
	}
}



2.netsniff.h

#include <stdio.h>
#include <pcap.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define SNAPLEN 65535		//	各种协议数据包大小都不超过65535
#define READ_TIMEOUT 500	//设置数据包抓取 超时时间,对pcap_dispatch,有效

pcap_if_t *g_tbNetCardInfo = NULL;
pthread_t g_pthreadStartCatch;

void main();
void findDevsTables();
void freeDevsTables();

void my_callback(u_char *useless,const struct pcap_pkthdr* pkthdr,const u_char*  packet);
void *start_catch(void *arg);





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值