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); } 然后,就可以初始化设备,开始接受网络包了: