本文介紹一個(gè)用C語言和網(wǎng)絡(luò)數(shù)據(jù)包分析開發(fā)工具實(shí)現(xiàn)的簡易網(wǎng)絡(luò)Sniffer。目前,已經(jīng)有不少的Sniff工具軟件,如Windows環(huán)境下,最富盛名的工具是Netxray和Sniffer pro,用它們?cè)?Windows環(huán)境下抓包來分析,非常方便。在UNIX環(huán)境下如Sniffit,Snoop,Tcpdump,Dsniff 等都是比較常見的。這里介紹一個(gè)用C語言和網(wǎng)絡(luò)數(shù)據(jù)包和分析開發(fā)工具libpcap及winpcap實(shí)現(xiàn)的簡易網(wǎng)絡(luò)Sniffer。
網(wǎng)絡(luò)嗅探器程序?qū)崿F(xiàn)
在c環(huán)境下編程,源碼如下:
/* June 2nd,2002
* Project for graduation qualification By Bby Team 19 */
#include
#include
//必須加路徑,必須把頭文件packet32.h包含進(jìn)去
#include "....Includepacket32.h"
#include "....Includentddndis.h"
#define Max_Num_Adapter 10
// Prototypes原形
//發(fā)包
void PrintPackets(LPPACKET lpPacket);
//設(shè)備列表
char AdapterList[Max_Num_Adapter][1024];
// 主程序開始
int main()
{
//define a pointer to an ADAPTER structure設(shè)備指針
LPADAPTER lpAdapter = 0;
//define a pointer to a PACKET structure包指針
LPPACKET lpPacket;
int i;
DWORD dwErrorCode;
DWORD dwVersion;
DWORD dwWindowsMajorVersion;
//Unicode strings (WinNT)
WCHAR AdapterName[8192]; //網(wǎng)絡(luò)適配器設(shè)備列表
WCHAR *temp,*temp1;
//ASCII strings (Win9x)
char AdapterNamea[8192]; //網(wǎng)絡(luò)適配器設(shè)備列表
char *tempa,*temp1a;
int AdapterNum=0,Open;
ULONG AdapterLength;
char buffer[256000]; // 容納來自驅(qū)動(dòng)器的數(shù)據(jù)的緩沖區(qū)
struct bpf_stat stat;
// 獲得本機(jī)網(wǎng)卡名
AdapterLength=4096;
printf("Packet.dll test application. Library version:%sn", PacketGetVersion());
printf("Adapters installed:n");
i=0;
下面這段代碼是用來在不同版本下得到網(wǎng)絡(luò)適配器名:
Win9x 和WinNT中的網(wǎng)卡名稱是分別用ASCII和UNICODE實(shí)現(xiàn)的,
所以首先要得到本地操作系統(tǒng)
的版本號(hào):
dwVersion=GetVersion();
dwWindowsMajorVersion= (DWORD)(LOBYTE(LOWORD(dwVersion)));
這里首先用到的Packet.dll函數(shù)是PacketGetAdapterNames(PTSTR pStr,
PULONG BufferSize,通常它是與驅(qū)動(dòng)程序通信并被調(diào)用的第一個(gè)函數(shù),
它將返回的用戶本地系統(tǒng)中安裝
的網(wǎng)絡(luò)適配器的名字放在
緩沖區(qū)pStr中;BufferSize是緩沖區(qū)的長度:
if (!(dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4))
{
//是Windows NT
// 找不到設(shè)備列表
if(PacketGetAdapterNames(AdapterName,&AdapterLength)==FALSE){
printf("Unable to retrieve the list of the adapters!n");
return -1;
}
// 找到設(shè)備列表
temp=AdapterName;
temp1=AdapterName;
while ((*temp!='')||(*(temp-1)!=''))
{
if (*temp=='')
{
memcpy(AdapterList[i],temp1,(temp-temp1)*2);
temp1=temp+1;
i++;
}
temp++;
}
// 顯示適配器列表
AdapterNum=i;
for (i=0;i wprintf(L"n%d- %sn",i+1,AdapterList[i]); printf("n"); } else //否則就是windows 9x,獲取適配器名的方法同WinNT下 { if(PacketGetAdapterNames(AdapterNamea,&AdapterLength)==FALSE){ printf("Unable to retrieve the list of the adapters!n"); return -1; } tempa=AdapterNamea; temp1a=AdapterNamea; while ((*tempa!='')||(*(tempa-1)!='')) { if (*tempa=='') { memcpy(AdapterList[i],temp1a,tempa-temp1a); temp1a=tempa+1; i++; } tempa++; } AdapterNum=i; for (i=0;i printf("n%d- %sn",i+1,AdapterList[i]); printf("n"); }