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);