if (!(dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4)) { //是Windows NT // 找不到設備列表 if(PacketGetAdapterNames(AdapterName,&AdapterLength)==FALSE){ printf("Unable to retrieve the list of the adapters!/n"); return -1; } // 找到設備列表 temp=AdapterName; temp1=AdapterName; while ((*temp!='/0')(*(temp-1)!='/0')) { if (*temp=='/0') { memcpy(AdapterList[i],temp1,(temp-temp1)*2); temp1=temp+1; i++; } temp++; } // 顯示適配器列表 AdapterNum=i; for (i=0;i<AdapterNum;i++) wprintf(L"/n%d- %s/n",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!='/0')(*(tempa-1)!='/0')) { if (*tempa=='/0') { memcpy(AdapterList[i],temp1a,tempa-temp1a); temp1a=tempa+1; i++; } tempa++; } AdapterNum=i; for (i=0;i<AdapterNum;i++) printf("/n%d- %s/n",i+1,AdapterList[i]); printf("/n"); } 下面這段代碼就是讓用戶選擇監聽的網絡適配器號:
// 選擇設備 do { printf("Select the number of the adapter to open : "); scanf("%d",&Open); if (Open>AdapterNum) printf("/nThe number must be smaller than %d",AdapterNum); } while (Open>AdapterNum);
然后,將所選擇的設備打開,這里可以設置為“混雜”模式打開,也可以是“直接”模式打開。代碼如下:
// 打開設備 lpAdapter = PacketOpenAdapter(AdapterList[Open-1]); // 當設備無法打開時,出示錯誤信息: if (!lpAdapter (lpAdapter->hFile == INVALID_HANDLE_VALUE)) { dwErrorCode=GetLastError(); printf("Unable to open the adapter, Error Code : %lx/n",dwErrorCode); return -1; } 將網卡設置為“混雜”模式,代碼如下:
// set the network adapter in promiscuous mode // 假如混雜模式設置失敗,提示錯誤: if(PacketSetHwFilter(lpAdapter,NDIS_PACKET_TYPE_PROMISCUOUS)==FALSE){ printf("Warning: unable to set promiscuous mode!/n"); } 然后在driver中置512K的緩沖:
// set a 512K buffer in the driver // 當無法設置緩沖區時,提示錯誤: if(PacketSetBuff(lpAdapter,512000)==FALSE){ printf("Unable to set the kernel buffer!/n"); return -1; }
// set a 1 second read timeout // 設置1秒的讀取操作超時 if(PacketSetReadTimeout(lpAdapter,1000)==FALSE){ printf("Warning: unable to set the read tiemout!/n"); } 接下來,定位設備,代碼如下:
//allocate and initialize a packet structure that will be used to //receive the packets. // 當定位失敗時,提示錯誤: if((lpPacket = PacketAllocatePacket())==NULL){ printf("/nError: failed to allocate the LPPACKET structure."); return (-1); } 然后,就可以初始化設備,開始接受網絡包了: