//发送数据包
bool SendPacket() { pcap_if_t* allAdapters = NULL; // 适配器列表 pcap_if_t* pAdapter = NULL; pcap_t* adapterHandle = NULL; u_char packet[20]; //发送数据包 char errorBuffer[PCAP_ERRBUF_SIZE+1] = {"0"}; if(pcap_findalldevs_ex(PCAP_SRC_IF_STRING,NULL,&allAdapters,errorBuffer) == -1) { fprintf(stderr,"non't excute pcap_findalldevs_ex,errorInfo:%s",errorBuffer); return -1; } if(allAdapters == NULL) { fprintf(stderr," not find the adapter for use!"); pcap_freealldevs(allAdapters); return 0; } int crtAdapter = 0; for(pAdapter = allAdapters; pAdapter;pAdapter = pAdapter->next) { printf("\nthe interface %d:%s",++crtAdapter,pAdapter->name); printf("\n---%s",pAdapter->description); } // 选择适配器 int nadapterNum = 0; printf(" Enter the number of adapter which you want to send packet!"); scanf("%d",&nadapterNum); // 搜索接口 if( nadapterNum < 1 || nadapterNum > crtAdapter ) { printf( "\nAdapter number out of range.\n" ); // 释放适配器列表 pcap_freealldevs( allAdapters ); return -1; } pAdapter = allAdapters; for( crtAdapter = 0; crtAdapter < nadapterNum - 1; crtAdapter++ ) pAdapter = pAdapter->next; // 打开指定适配器 adapterHandle = pcap_open( pAdapter->name, // name of the adapter 65536, // portion of the packet to capture // 65536 guarantees that the whole // packet will be captured PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode 1000, // read timeout - 1 millisecond NULL, // authentication on the remote machine errorBuffer // error buffer ); if( adapterHandle == NULL ) {//指定适配器打开失败 fprintf( stderr, "\nUnable to open the adapter\n", pAdapter->name ); // 释放适配器列表 pcap_freealldevs( allAdapters ); return -1; } pcap_freealldevs( allAdapters );//释放适配器列表 //创建数据封包 // 设置目标的MAC地址为01 : 01 : 01 : 01 : 01 : 01 packet[0] = 0x01; packet[1] = 0x01; packet[2] = 0x01; packet[3] = 0x01; packet[4] = 0x01; packet[5] = 0x01; // 设置源的MAC地址为02 : 02 : 02 : 02 : 02 : 02 packet[6] = 0x02; packet[7] = 0x02; packet[8] = 0x02; packet[9] = 0x02; packet[10] = 0x02; packet[11] = 0x02; // 设置封包其他部分内容 for( int index = 12; index < 20; index++ ) { packet[index] = 0xC4; } //发送数据封包 if( pcap_sendpacket( adapterHandle, // the adapter handle packet, // the packet 20 // the length of the packet ) != 0 ) { fprintf( stderr,"\nError sending the packet: \n", pcap_geterr( adapterHandle ) ); return -1; } return 0; }