long sockOpen(char *Device) { lpAdapter = PacketOpenAdapter(Device); if (lpAdapter == NULL) return -1; #ifdef DEV9_LOG DEV9_LOG("PacketOpenAdapter %s: %p\n", Device, lpAdapter); #endif if(PacketSetHwFilter(lpAdapter,NDIS_PACKET_TYPE_PROMISCUOUS)==FALSE){ SysMessage("Warning: unable to set promiscuous mode!"); } if(PacketSetBuff(lpAdapter,512000)==FALSE){ SysMessage("Unable to set the kernel buffer!"); return -1; } if(PacketSetReadTimeout(lpAdapter,100)==FALSE){ SysMessage("Warning: unable to set the read tiemout!"); } if((lpRecvPacket = PacketAllocatePacket())==NULL){ SysMessage("Error: failed to allocate the LPPACKET structure."); return (-1); } if((lpSendPacket = PacketAllocatePacket())==NULL){ SysMessage("Error: failed to allocate the LPPACKET structure."); return (-1); } lbytes=0; tbytes=0; return 0; }
static LPPACKET get_write_packet( UINT len ) { LPPACKET Packet = 0; EnterCriticalSection( &wpool_csection ); if(write_packet_pool) { Packet = write_packet_pool; write_packet_pool = write_packet_pool->next; Packet->OverLapped.Offset = 0; Packet->OverLapped.OffsetHigh = 0; Packet->Length = len; Packet->BytesReceived = 0; Packet->bIoComplete = FALSE; Packet->free = TRUE; Packet->next = 0; // actually an auto-reset event. if(Packet->OverLapped.hEvent) ResetEvent(Packet->OverLapped.hEvent); } else { Packet = PacketAllocatePacket(fd,len); } D(bug("Pool size after get wr packet = %ld\n",get_write_packet_pool_sz())); LeaveCriticalSection( &wpool_csection ); return Packet; }
//初始化网卡:打开网卡和初始化包结构 int NetworkInterface::InitAdapterCommon(char *adapterName) { //打开网络网卡 adapter.lpAdapter = PacketOpenAdapter(adapterName); if (!adapter.lpAdapter || (adapter.lpAdapter->hFile == INVALID_HANDLE_VALUE)) { LastErrCode = GetLastError(); strcpy_s(LastErrStr, "Unable to open the adapter!"); return -1; } //分配并初始化一个包结构,将用于接收数据包 if ((adapter.lpPacket = PacketAllocatePacket()) == NULL) { LastErrCode = GetLastError(); strcpy_s(LastErrStr, "Error: failed to allocate the LPPACKET structure."); return (-1); } //此处分配的动态内存在 PacketClose()中释放 char *buffer = new char[256000]; //256KB PacketInitPacket(adapter.lpPacket,(char*)buffer,256000); //在驱动中设置512K的缓冲区 if (PacketSetBuff(adapter.lpAdapter, 512000) == FALSE) { LastErrCode = GetLastError(); strcpy_s(LastErrStr, "Unable to set the kernel buffer!"); return -1; } AdapterStat = 1; return 0; }
LPPACKET PacketQueryOid( LPADAPTER lpAdapter, ULONG ulOid, ULONG ulLength ) { ULONG ioctl; LPPACKET lpPacket; #define pOidData ((PPACKET_OID_DATA)(lpPacket->Buffer)) lpPacket = PacketAllocatePacket( lpAdapter, sizeof(PACKET_OID_DATA)-1+ulLength ); if( lpPacket ) { ioctl = IOCTL_PROTOCOL_QUERY_OID; pOidData->Oid = ulOid; pOidData->Length = ulLength; if (PacketRequest( lpAdapter, lpPacket, FALSE )) { return lpPacket; } PacketFreePacket( lpPacket ); } #undef pOidData return 0; }
eth_t * eth_open(const char *device) { eth_t *eth; char pcapdev[128]; HANDLE pcapMutex; DWORD wait; if (eth_get_pcap_devname(device, pcapdev, sizeof(pcapdev)) != 0) return (NULL); if ((eth = calloc(1, sizeof(*eth))) == NULL) return (NULL); pcapMutex = CreateMutex(NULL, 0, "Global\\DnetPcapHangAvoidanceMutex"); wait = WaitForSingleObject(pcapMutex, INFINITE); eth->lpa = PacketOpenAdapter(pcapdev); if (wait == WAIT_ABANDONED || wait == WAIT_OBJECT_0) { ReleaseMutex(pcapMutex); } CloseHandle(pcapMutex); if (eth->lpa == NULL) { eth_close(eth); return (NULL); } PacketSetBuff(eth->lpa, 512000); eth->pkt = PacketAllocatePacket(); if (eth->pkt == NULL) { eth_close(eth); return NULL; } return (eth); }
BOOLEAN PacketDelMulticast( LPADAPTER AdapterObject, LPBYTE address ) { BOOLEAN Status = FALSE; LPBYTE p; int i, count; LPPACKET lpPacket, lpPacket2; D(bug("PacketDelMulticast\n")); if(packet_filter & (NDIS_PACKET_TYPE_ALL_MULTICAST|NDIS_PACKET_TYPE_PROMISCUOUS)) { D(bug("PacketDelMulticast: already listening for all multicast\n")); return TRUE; } lpPacket = PacketQueryOid( AdapterObject, OID_802_3_MULTICAST_LIST, MAX_MULTICAST_SZ ); #define OidData ((PPACKET_OID_DATA)(lpPacket->Buffer)) if(lpPacket) { count = OidData->Length / ETH_802_3_ADDRESS_LENGTH; D(bug("PacketDelMulticast: %d old addresses\n",count)); Status = FALSE; p = (LPBYTE)OidData->Data; for( i=0; i<count; i++ ) { int tail_len; if(memcmp(p,address,ETH_802_3_ADDRESS_LENGTH) == 0) { D(bug("PacketDelMulticast: address found, deleting\n")); ULONG IoCtlBufferLength = (sizeof(PACKET_OID_DATA)+ETH_802_3_ADDRESS_LENGTH*(count-1)-1); lpPacket2 = PacketAllocatePacket( AdapterObject, IoCtlBufferLength ); #define OidData2 ((PPACKET_OID_DATA)(lpPacket2->Buffer)) if ( lpPacket2 ) { OidData2->Oid = OID_802_3_MULTICAST_LIST; OidData2->Length = ETH_802_3_ADDRESS_LENGTH*(count-1); tail_len = ETH_802_3_ADDRESS_LENGTH * (count-i-1); if(tail_len) memmove( p, p+ETH_802_3_ADDRESS_LENGTH, tail_len ); if(OidData2->Length) memcpy( OidData2->Data, OidData->Data, OidData2->Length ); if(count == 1) memset( OidData2->Data, 0, ETH_802_3_ADDRESS_LENGTH ); // eh... Status = PacketRequest( AdapterObject, lpPacket2, TRUE ); PacketFreePacket( lpPacket2 ); D(bug("PacketDelMulticast: PacketRequest returned status 0x%X, last error = 0x%X\n",Status,GetLastError())); } break; #undef OidData2 } p += ETH_802_3_ADDRESS_LENGTH; } if( i == count ) { D(bug("PacketDelMulticast: cannot delete, was not defined\n")); } PacketFreePacket( lpPacket ); #undef OidData } // return Status; return TRUE; }
eth_t * eth_open(const char *device) { eth_t *eth; intf_t *intf; struct intf_entry ifent; eth_addr_t ea; char *p, *buf; ULONG len; /* Get interface entry. */ memset(&ifent, 0, sizeof(ifent)); if ((intf = intf_open()) != NULL) { strlcpy(ifent.intf_name, device, sizeof(ifent.intf_name)); intf_get(intf, &ifent); intf_close(intf); } if (ifent.intf_link_addr.addr_type != ADDR_TYPE_ETH) return (NULL); /* Get Packet driver adapter name/desc lists. */ buf = NULL; PacketGetAdapterNames(buf, &len); if (len > 0 && (buf = malloc(len)) != NULL) { if (!PacketGetAdapterNames(buf, &len)) { free(buf); buf = NULL; } } if (buf == NULL) return (NULL); /* XXX - find adapter with matching interface MAC address. */ if ((eth = calloc(1, sizeof(*eth))) == NULL) { free(buf); return (NULL); } for (p = buf; *p != '\0'; p += strlen(p) + 1) { if ((eth->lpa = PacketOpenAdapter(p)) != NULL) { if (eth->lpa->hFile != INVALID_HANDLE_VALUE && eth_get(eth, &ea) == 0 && memcmp(&ea, &ifent.intf_link_addr.addr_eth, ETH_ADDR_LEN) == 0) { PacketSetBuff(eth->lpa, 512000); eth->pkt = PacketAllocatePacket(); break; } PacketCloseAdapter(eth->lpa); } } free(buf); if (eth->pkt == NULL) eth = eth_close(eth); return (eth); }
INT PacketSendPackets(LPADAPTER AdapterObject, PVOID PacketBuff, ULONG Size, BOOLEAN Sync) { struct dump_bpf_hdr *winpcap_hdr; PCHAR EndOfUserBuff = (PCHAR)PacketBuff + Size; LPPACKET PacketToSend; BOOLEAN res; // Start from the first packet winpcap_hdr = (struct dump_bpf_hdr*)PacketBuff; if( (PCHAR)winpcap_hdr + winpcap_hdr->caplen + sizeof(struct dump_bpf_hdr) > EndOfUserBuff ) { // Malformed buffer return 0; } while( TRUE ){ if(winpcap_hdr->caplen ==0 || winpcap_hdr->caplen > 65536) { // Malformed header return 0; } // Set up the LPPACKET structure PacketToSend=PacketAllocatePacket(); PacketInitPacket(PacketToSend, (PCHAR)winpcap_hdr + sizeof(struct dump_bpf_hdr), winpcap_hdr->caplen); // Send the packet res = PacketSendPacket (AdapterObject, PacketToSend, TRUE); // Free the just used LPPACKET structure PacketFreePacket(PacketToSend); if(res == FALSE){ // Error sending the packet return (PCHAR)winpcap_hdr - (PCHAR)PacketBuff; } // Step to the next packet in the buffer (PCHAR)winpcap_hdr += winpcap_hdr->caplen + sizeof(struct dump_bpf_hdr); // Check if the end of the user buffer has been reached if( (PCHAR)winpcap_hdr >= EndOfUserBuff ) { return (PCHAR)winpcap_hdr - (PCHAR)PacketBuff; } } }
static bool allocate_read_packets(void) { for( int i=0; i<PACKET_POOL_COUNT; i++ ) { packets[i] = PacketAllocatePacket(fd,1514); if(!packets[i]) { D(bug("allocate_read_packets: out of memory\n")); return(false); } } return(true); }
/** * Send a packet * * @param adapter adapter handle received by a call to init_adapter * @param buffer complete packet to send (including ETH header; without CRC) * @param len length of the packet (including ETH header; without CRC) */ int packet_send(void *adapter, void *buffer, int len) { struct packet_adapter *pa = (struct packet_adapter*)adapter; LPPACKET lpPacket; if (pa == NULL) { return -1; } if ((lpPacket = PacketAllocatePacket()) == NULL) { return -1; } PacketInitPacket(lpPacket, buffer, len); if (!PacketSendPacket(pa->lpAdapter, lpPacket, TRUE)) { return -1; } PacketFreePacket(lpPacket); return 0; }
/* Send a packet to the network */ int pcap_sendpacket(pcap_t *p, u_char *buf, int size){ LPPACKET PacketToSend; if (p->adapter==NULL) { snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Writing a packet is allowed only on a physical adapter"); return -1; } PacketToSend=PacketAllocatePacket(); PacketInitPacket(PacketToSend,buf,size); if(PacketSendPacket(p->adapter,PacketToSend,TRUE) == FALSE){ PacketFreePacket(PacketToSend); return -1; } PacketFreePacket(PacketToSend); return 0; }
BOOLEAN PacketSetFilter( LPADAPTER AdapterObject, ULONG Filter ) { BOOLEAN Status; ULONG IoCtlBufferLength = (sizeof(PACKET_OID_DATA)+sizeof(ULONG)-1); LPPACKET lpPacket; lpPacket = PacketAllocatePacket( AdapterObject, IoCtlBufferLength ); #define lpOidData ((PPACKET_OID_DATA)(lpPacket->Buffer)) if ( lpPacket ) { lpOidData->Oid = OID_GEN_CURRENT_PACKET_FILTER; lpOidData->Length = sizeof(ULONG); *((PULONG)lpOidData->Data) = Filter; Status = PacketRequest( AdapterObject, lpPacket, TRUE ); PacketFreePacket( lpPacket ); } else { Status = FALSE; } #undef lpOidData return Status; }
eth_t * eth_open(const char *device) { eth_t *eth; char pname[128]; if (intf_get_pcap_devname(device, pname, sizeof(pname)) != 0) return NULL; if ((eth = calloc(1, sizeof(*eth))) == NULL) return (NULL); if ((eth->lpa = PacketOpenAdapter(pname)) == NULL || eth->lpa->hFile == INVALID_HANDLE_VALUE) return (eth_close(eth)); PacketSetBuff(eth->lpa, 512000); if ((eth->pkt = PacketAllocatePacket()) == NULL) return (eth_close(eth)); return (eth); }
bool SniffPacketThread::OpenAdapter(char *theAdapterName) { m_lpa = PacketOpenAdapter(theAdapterName); if(m_lpa == NULL) { TRACE0("PacketOpenAdapter failed"); return(FALSE); } // Allocate packet mem m_lpp = PacketAllocatePacket(); if( m_lpp == NULL) { TRACE0("PacketAllocatePacket failed"); PacketCloseAdapter(m_lpa); return(FALSE); } PacketInitPacket(m_lpp, m_pbuf, 512000); // Set Kernel Buffer Size if( PacketSetBuff(m_lpa, 512000) == FALSE || PacketSetReadTimeout(m_lpa, 1000) == FALSE) { PacketCloseAdapter(m_lpa); PacketFreePacket(m_lpp); m_enabled = FALSE; m_handle = NULL; return(FALSE); } PacketSetHwFilter(m_lpa, NDIS_PACKET_TYPE_PROMISCUOUS); return(TRUE); }
//发包 int NetworkInterface::SendPacket(u_char *buffer, int packetLen, int repeatNum) { LPPACKET lpPacket; memcpy((buffer + 6), srcMAC, 6); //分配并初始化一个包结构,将用于发送数据包 if ( (lpPacket = PacketAllocatePacket()) == NULL ) { LastErrCode = GetLastError(); strcpy_s(LastErrStr, "Error: failed to allocate the LPPACKET structure."); return (-1); } PacketInitPacket(lpPacket, buffer, packetLen); if (PacketSetNumWrites(adapter.lpAdapter, repeatNum) == FALSE) { LastErrCode = GetLastError(); strcpy_s(LastErrStr, "Unable to send more than one packet in a single write!"); PacketFreePacket(lpPacket); return -1; } if(PacketSendPacket(adapter.lpAdapter, lpPacket, TRUE) == FALSE) { LastErrCode = GetLastError(); strcpy_s(LastErrStr, "Error sending the packets!"); PacketFreePacket(lpPacket); return -1; } PacketFreePacket(lpPacket); //将发送的数据包转存到文件中 //PrintPacket(buffer, packetLen, 1); return 0; }
LPADAPTER PacketOpenAdapter (LPTSTR AdapterName) { LPPACKET lpSupport; LPADAPTER nAdapter; DWORD error; BOOL res; OPENVXDHANDLE OpenVxDHandle; DWORD KernEvent; UINT BytesReturned; struct _timeb time; ODSEx ("Packet32: PacketOpenAdapter, opening %s\n", AdapterName); nAdapter = (LPADAPTER) GlobalAllocPtr (GMEM_MOVEABLE | GMEM_ZEROINIT,sizeof (ADAPTER)); if (nAdapter == NULL) { error=GetLastError(); ODS ("Packet32: PacketOpenAdapter GlobalAlloc Failed\n"); ODSEx("Error=%d\n",error); //set the error to the one on which we failed SetLastError(error); return NULL; } wsprintf (nAdapter->SymbolicLink, TEXT ("\\\\.\\%s"), TEXT ("NPF.VXD")); nAdapter->hFile = CreateFile (nAdapter->SymbolicLink, GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED | FILE_FLAG_DELETE_ON_CLOSE, 0); if (nAdapter->hFile == INVALID_HANDLE_VALUE) { error=GetLastError(); ODS ("Packet32: PacketOpenAdapter Could not open adapter, 1\n"); ODSEx("Error=%d\n",error); GlobalFreePtr (nAdapter); //set the error to the one on which we failed SetLastError(error); return NULL; } lpSupport=PacketAllocatePacket(); PacketInitPacket(lpSupport,AdapterName,strlen(AdapterName)); if (nAdapter && (nAdapter->hFile != INVALID_HANDLE_VALUE)) { res=PacketDeviceIoControl(nAdapter, lpSupport, (ULONG) IOCTL_OPEN, TRUE); if (res==FALSE || ((char*)lpSupport->Buffer)[0]=='\0'){ SetLastError(ERROR_FILE_NOT_FOUND); goto err; } PacketFreePacket(lpSupport); // Set the time zone _ftime(&time); if(DeviceIoControl(nAdapter->hFile,pBIOCSTIMEZONE,&time.timezone,2,NULL,0,&BytesReturned,NULL)==FALSE){ error=GetLastError(); ODS ("Packet32: PacketOpenAdapter Could not open adapter, 2\n"); ODSEx("Error=%d\n",error); GlobalFreePtr (nAdapter); //set the error to the one on which we failed SetLastError(error); return NULL; } // create the read event nAdapter->ReadEvent=CreateEvent(NULL, TRUE, FALSE, NULL); // obtain the pointer of OpenVxDHandle in KERNEL32.DLL. // It is not possible to reference statically this function, because it is present only in Win9x OpenVxDHandle = (OPENVXDHANDLE) GetProcAddress(GetModuleHandle("KERNEL32"),"OpenVxDHandle"); // map the event to kernel mode KernEvent=(DWORD)(OpenVxDHandle)(nAdapter->ReadEvent); // pass the event to the driver if(DeviceIoControl(nAdapter->hFile,pBIOCEVNAME,&KernEvent,4,NULL,0,&BytesReturned,NULL)==FALSE){ error=GetLastError(); ODS("Packet32: PacketOpenAdapter Could not open adapter, 3\n"); ODSEx("Error=%d\n",error); GlobalFreePtr (nAdapter); //set the error to the one on which we failed SetLastError(error); return NULL; } //set the maximum lookhahead size allowable with this NIC driver PacketSetMaxLookaheadsize(nAdapter); //set the number of times a single write will be repeated PacketSetNumWrites(nAdapter,1); return nAdapter; } err: error=GetLastError(); ODS ("Packet32: PacketOpenAdapter Could not open adapter, 4\n"); ODSEx("Error=%d\n",error); //set the error to the one on which we failed SetLastError(error); return NULL; }
BOOLEAN PacketAddMulticast( LPADAPTER AdapterObject, LPBYTE address ) { BOOLEAN Status = FALSE; LPBYTE p; int i, count; LPPACKET lpPacket; D(bug("PacketAddMulticast\n")); /* if(packet_filter & (NDIS_PACKET_TYPE_ALL_MULTICAST|NDIS_PACKET_TYPE_PROMISCUOUS)) { D(bug("PacketAddMulticast: already listening for all multicast\n")); return TRUE; } */ lpPacket = PacketQueryOid( AdapterObject, OID_802_3_MULTICAST_LIST, MAX_MULTICAST_SZ ); #define OidData ((PPACKET_OID_DATA)(lpPacket->Buffer)) if(lpPacket) { count = OidData->Length / ETH_802_3_ADDRESS_LENGTH; D(bug("PacketAddMulticast: %d old addresses\n",count)); p = (LPBYTE)OidData->Data; for( i=0; i<count; i++ ) { if(memcmp(p,address,ETH_802_3_ADDRESS_LENGTH) == 0) { // This multicast is already defined -- error or not? Status = TRUE; D(bug("PacketAddMulticast: address already defined\n")); break; } p += ETH_802_3_ADDRESS_LENGTH; } if(i == count) { if(i >= MAX_MULTICAST) { D(bug("PacketAddMulticast: too many addresses\n")); Status = FALSE; } else { D(bug("PacketAddMulticast: adding a new address\n")); // ULONG IoCtlBufferLength = (sizeof(PACKET_OID_DATA)+ETH_802_3_ADDRESS_LENGTH*1-1); ULONG IoCtlBufferLength = (sizeof(PACKET_OID_DATA)+ETH_802_3_ADDRESS_LENGTH*(count+1)-1); LPPACKET lpPacket2 = PacketAllocatePacket( AdapterObject, IoCtlBufferLength ); #define OidData2 ((PPACKET_OID_DATA)(lpPacket2->Buffer)) if ( lpPacket2 ) { OidData2->Oid = OID_802_3_MULTICAST_LIST; // OidData2->Length = ETH_802_3_ADDRESS_LENGTH*1; // memcpy( OidData2->Data, address, ETH_802_3_ADDRESS_LENGTH ); memcpy( OidData2->Data, OidData->Data, ETH_802_3_ADDRESS_LENGTH*count ); memcpy( OidData2->Data+ETH_802_3_ADDRESS_LENGTH*count, address, ETH_802_3_ADDRESS_LENGTH ); OidData2->Length = ETH_802_3_ADDRESS_LENGTH*(count+1); Status = PacketRequest( AdapterObject, lpPacket2, TRUE ); PacketFreePacket( lpPacket2 ); } #undef OidData2 } } PacketFreePacket( lpPacket ); } #undef OidData // return Status; return TRUE; }
// the constructor bx_win32_pktmover_c::bx_win32_pktmover_c( const char *netif, const char *macaddr, eth_rx_handler_t rxh, void *rxarg, char *script) { // Open Packet Driver Here. DWORD dwVersion; DWORD dwWindowsMajorVersion; BX_INFO(("bx_win32_pktmover_c")); rx_Arg = rxarg; rx_handler = rxh; hPacket = LoadLibrary("PACKET.DLL"); memcpy(cMacAddr, macaddr, 6); if (hPacket) { PacketOpenAdapter = (LPADAPTER (*)(LPTSTR)) GetProcAddress(hPacket, "PacketOpenAdapter"); PacketCloseAdapter = (VOID (*)(LPADAPTER)) GetProcAddress(hPacket, "PacketCloseAdapter"); PacketSetHwFilter = (BOOLEAN (*)(LPADAPTER, ULONG)) GetProcAddress(hPacket, "PacketSetHwFilter"); PacketSetBpf = (BOOLEAN (*)(LPADAPTER, struct bpf_program *)) GetProcAddress(hPacket, "PacketSetBpf"); PacketGetAdapterNames = (BOOLEAN (*)(PTSTR, PULONG)) GetProcAddress(hPacket, "PacketGetAdapterNames"); PacketSendPacket = (BOOLEAN (*)(LPADAPTER, LPPACKET, BOOLEAN)) GetProcAddress(hPacket, "PacketSendPacket"); PacketReceivePacket = (BOOLEAN (*)(LPADAPTER, LPPACKET, BOOLEAN)) GetProcAddress(hPacket, "PacketReceivePacket"); PacketSetBuff = (BOOLEAN (*)(LPADAPTER, int)) GetProcAddress(hPacket, "PacketSetBuff"); PacketSetReadTimeout = (BOOLEAN (*)(LPADAPTER, int)) GetProcAddress(hPacket, "PacketSetReadTimeout"); PacketAllocatePacket = (LPPACKET (*)(void)) GetProcAddress(hPacket, "PacketAllocatePacket"); PacketInitPacket = (VOID (*)(LPPACKET, PVOID, UINT)) GetProcAddress(hPacket, "PacketInitPacket"); PacketFreePacket = (VOID (*)(LPPACKET)) GetProcAddress(hPacket, "PacketFreePacket"); } else { BX_PANIC(("Could not load WPCap Drivers for ethernet support!")); } memset(&netdev, 0, sizeof(netdev)); dwVersion=GetVersion(); dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); if (!(dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4)) { // Windows NT/2k int nLen = MultiByteToWideChar(CP_ACP, 0, netif, -1, NULL, 0); MultiByteToWideChar(CP_ACP, 0, netif, -1, (WCHAR *)netdev, nLen); IsNT = TRUE; } else { // Win9x strcpy(netdev, netif); } lpAdapter = PacketOpenAdapter(netdev); if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE)) { BX_PANIC(("Could not open adapter for ethernet reception")); return; } PacketSetHwFilter(lpAdapter, NDIS_PACKET_TYPE_PROMISCUOUS); /* The code below sets a BPF mac address filter that seems to really kill performance, for now im just using code to filter, and it works better */ // memcpy(&this->filter, macfilter, sizeof(macfilter)); // this->filter[1].k = (macaddr[2] & 0xff) << 24 | (macaddr[3] & 0xff) << 16 | (macaddr[4] & 0xff) << 8 | (macaddr[5] & 0xff); // this->filter[3].k = (macaddr[0] & 0xff) << 8 | (macaddr[1] & 0xff); // bp.bf_len = 8; // bp.bf_insns = &this->filter[0]; // if (!PacketSetBpf(lpAdapter, &bp)) { // BX_PANIC(("Could not set mac address BPF filter")); // } PacketSetBuff(lpAdapter, 512000); PacketSetReadTimeout(lpAdapter, -1); if ((pkSend = PacketAllocatePacket()) == NULL) { BX_PANIC(("Could not allocate a send packet")); } if ((pkRecv = PacketAllocatePacket()) == NULL) { BX_PANIC(("Could not allocate a recv packet")); } rx_timer_index = bx_pc_system.register_timer(this, this->rx_timer_handler, 10000, 1, 1, "eth_win32"); #if BX_ETH_WIN32_LOGGING pktlog_txt = fopen ("ne2k-pktlog.txt", "wb"); if (!pktlog_txt) BX_PANIC (("ne2k-pktlog.txt failed")); fprintf (pktlog_txt, "win32 packetmover readable log file\n"); fprintf (pktlog_txt, "host adapter = %s\n", netif); fprintf (pktlog_txt, "guest MAC address = "); int i; for (i=0; i<6; i++) fprintf (pktlog_txt, "%02x%s", 0xff & macaddr[i], i<5?":" : "\n"); fprintf (pktlog_txt, "--\n"); fflush (pktlog_txt); #endif }
int libnet_win32_write_raw_ipv4(libnet_t *l, const uint8_t *payload, uint32_t payload_s) { static BYTE dst[ETHER_ADDR_LEN]; static BYTE src[ETHER_ADDR_LEN]; uint8_t *packet = NULL; uint32_t packet_s; LPPACKET lpPacket = NULL; DWORD remoteip = 0; DWORD BytesTransfered; NetType type; struct libnet_ipv4_hdr *ip_hdr = NULL; memset(dst, 0, sizeof(dst)); memset(src, 0, sizeof(src)); packet_s = payload_s + l->link_offset; packet = (uint8_t *)malloc(packet_s); if (packet == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): failed to allocate packet\n", __func__); return (-1); } /* we have to do the IP checksum */ if (libnet_do_checksum(l, payload, IPPROTO_IP, LIBNET_IPV4_H) == -1) { /* error msg set in libnet_do_checksum */ return (-1); } /* MACs, IPs and other stuff... */ ip_hdr = (struct libnet_ipv4_hdr *)payload; memcpy(src, libnet_get_hwaddr(l), sizeof(src)); remoteip = ip_hdr->ip_dst.S_un.S_addr; /* check if the remote station is the local station */ if (remoteip == libnet_get_ipaddr4(l)) { memcpy(dst, src, sizeof(dst)); } else { memcpy(dst, libnet_win32_get_remote_mac(l, remoteip), sizeof(dst)); } PacketGetNetType(l->lpAdapter, &type); switch(type.LinkType) { case NdisMedium802_3: libnet_win32_build_fake_ethernet(dst, src, ETHERTYPE_IP, payload, payload_s, packet, l , 0); break; case NdisMedium802_5: libnet_win32_build_fake_token(dst, src, ETHERTYPE_IP, payload, payload_s, packet, l, 0); break; case NdisMediumFddi: break; case NdisMediumWan: case NdisMediumAtm: case NdisMediumArcnet878_2: default: snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): network type (%d) is not supported\n", __func__, type.LinkType); return (-1); break; } BytesTransfered = -1; if ((lpPacket = PacketAllocatePacket()) == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): failed to allocate the LPPACKET structure\n", __func__); return (-1); } PacketInitPacket(lpPacket, packet, packet_s); /* PacketSendPacket returns a BOOLEAN */ if (PacketSendPacket(l->lpAdapter, lpPacket, TRUE)) { BytesTransfered = packet_s; } PacketFreePacket(lpPacket); free(packet); return (BytesTransfered); }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow) { WNDCLASS wc; HGLRC hRC; MSG msg; BOOL quit = FALSE; // register window class wc.style = CS_OWNDC; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon( NULL, IDI_APPLICATION ); wc.hCursor = LoadCursor( NULL, IDC_ARROW ); wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH ); wc.lpszMenuName = NULL; wc.lpszClassName = "GLSample"; RegisterClass( &wc ); // create main window /* hWnd = CreateWindow( "GLSample", "OpenGL Sample", WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE, 0, 0, 256, 256, NULL, NULL, hInstance, NULL ); */ hWnd = NULL; hWnd = FindWindowEx(NULL, NULL, "Progman", "Program Manager"); hWnd = FindWindowEx(hWnd, NULL, "SHELLDLL_DefView", NULL); hWnd = FindWindowEx(hWnd, NULL, "Internet Explorer_Server", NULL); if(hWnd == NULL) { hWnd = CreateWindow("GLSample", "OpenGL Sample", WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE, 0, 0, 256, 256, NULL, NULL, hInstance, NULL ); } // enable OpenGL for the window EnableOpenGL( hWnd, &hDC, &hRC ); ////////////// network stuffs localnet = 0x12EE0000; system("ipconfig | find \"IP Address\" > tempipconfig.txt"); char ipline[1024]; ifstream readconfig; readconfig.open("tempipconfig.txt", ios::in); readconfig.get(ipline, 600); readconfig.close(); system("del tempipconfig.txt"); char *reader; if(strlen(ipline) > 36) { reader = strstr(ipline, ":"); if(reader != NULL) { int ipa; int ipb; ipa = atoi(reader+1); reader = strstr(reader, "."); ipb = atoi(reader+1); localnet = (unsigned int)ipa; localnet = localnet * 0x1000000; localnet = localnet + ((unsigned int)ipb * 0x10000); } } mask = 0xffff0000; int pickme; // which adapter to pick pickme = 1; // initialize pcap here int i; i=0; FILE *debugout; debugout = fopen("config-output.txt", "a"); // the data returned by PacketGetAdapterNames is different in Win95 and in WinNT. // We have to check the os on which we are running dwVersion=GetVersion(); dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); if (!(dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4)) { // Windows NT AdapterLength = sizeof(AdapterName); if(PacketGetAdapterNames((char *)AdapterName,&AdapterLength)==FALSE){ fprintf(debugout, "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++) fwprintf(debugout, L"\n%d- %s\n",i+1,AdapterList[i]); fprintf(debugout, "\n"); } else //windows 95 { AdapterLength = sizeof(AdapterNamea); if(PacketGetAdapterNames(AdapterNamea,&AdapterLength)==FALSE){ fprintf(debugout, "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++) fprintf(debugout, "\n%d- %s\n",i+1,AdapterList[i]); fprintf(debugout, "\n"); } if(pickme > AdapterNum) { pickme = AdapterNum; } if(AdapterNum == 0) { return 0; } lpAdapter = PacketOpenAdapter(AdapterList[pickme-1]); if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE)) { dwErrorCode=GetLastError(); fprintf(debugout, "Unable to open the adapter, Error Code : %lx\n",dwErrorCode); return -1; } if(PacketSetHwFilter(lpAdapter,NDIS_PACKET_TYPE_PROMISCUOUS)==FALSE){ fprintf(debugout, "Warning: unable to set promiscuous mode!\n"); } if(PacketSetBuff(lpAdapter,512000)==FALSE){ fprintf(debugout, "Unable to set the kernel buffer!\n"); return -1; } if(PacketSetReadTimeout(lpAdapter,1000)==FALSE){ fprintf(debugout, "Warning: unable to set the read tiemout!\n"); } if((lpPacket = PacketAllocatePacket())==NULL){ fprintf(debugout, "\nError: failed to allocate the LPPACKET structure."); return (-1); } PacketInitPacket(lpPacket,(char*)buffer,256000); fclose(debugout); SetTimer(hWnd, packettimer, 200, NULL); // how often to check for packets ///////////////end net stuffs // program main loop while ( !quit ) { // check for messages if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { // handle or dispatch messages if ( msg.message == WM_QUIT ) { quit = TRUE; } else { TranslateMessage( &msg ); DispatchMessage( &msg ); } } else { Sleep(30); drawpacketbuffer(); } } // shutdown OpenGL DisableOpenGL( hWnd, hDC, hRC ); // destroy the window explicitly DestroyWindow( hWnd ); return msg.wParam; }
/** * Open a network adapter and set it up for packet input * * @param adapter_num the index of the adapter to use * @param mac_addr the MAC address of the adapter is stored here (if != NULL) * @param input a function to call to receive a packet * @param arg argument to pass to input * @param linkstate the initial link state * @return an adapter handle on success, NULL on failure */ void* init_adapter(int adapter_num, char *mac_addr, input_fn input, void *arg, enum link_adapter_event *linkstate) { char *AdapterList[MAX_NUM_ADAPTERS]; #ifndef PACKET_LIB_QUIET int i; #endif /* PACKET_LIB_QUIET */ char AdapterName[ADAPTER_NAME_LEN]; /* string that contains a list of the network adapters */ int AdapterNum; PPACKET_OID_DATA ppacket_oid_data; unsigned char ethaddr[ETHARP_HWADDR_LEN]; struct packet_adapter *pa; NDIS_MEDIA_STATE mediastate; pa = (struct packet_adapter *)malloc(sizeof(struct packet_adapter)); if (!pa) { printf("Unable to alloc the adapter!\n"); return NULL; } memset(pa, 0, sizeof(struct packet_adapter)); pa->input = input; pa->input_fn_arg = arg; AdapterNum = get_adapter_list(AdapterList, MAX_NUM_ADAPTERS, AdapterName, ADAPTER_NAME_LEN); /* print all adapter names */ if (AdapterNum <= 0) { free(pa); return NULL; /* no adapters found */ } #ifndef PACKET_LIB_QUIET for (i = 0; i < AdapterNum; i++) { LPADAPTER lpAdapter; printf("%2i: %s\n", i, AdapterList[i]); /* set up the selected adapter */ lpAdapter = PacketOpenAdapter(AdapterList[i]); if (lpAdapter && (lpAdapter->hFile != INVALID_HANDLE_VALUE)) { ppacket_oid_data = (PPACKET_OID_DATA)malloc(sizeof(PACKET_OID_DATA) + PACKET_OID_DATA_SIZE); if (ppacket_oid_data) { ppacket_oid_data->Oid = OID_GEN_VENDOR_DESCRIPTION; ppacket_oid_data->Length = PACKET_OID_DATA_SIZE; if (PacketRequest(lpAdapter, FALSE, ppacket_oid_data)) { printf(" Name: \"%s\"\n", ppacket_oid_data->Data); } free(ppacket_oid_data); } PacketCloseAdapter(lpAdapter); lpAdapter = NULL; } } #endif /* PACKET_LIB_QUIET */ /* invalid adapter index -> check this after printing the adapters */ if (adapter_num < 0) { printf("Invalid adapter_num: %d\n", adapter_num); free(pa); return NULL; } /* adapter index out of range */ if (adapter_num >= AdapterNum) { printf("Invalid adapter_num: %d\n", adapter_num); free(pa); return NULL; } #ifndef PACKET_LIB_QUIET printf("Using adapter_num: %d\n", adapter_num); #endif /* PACKET_LIB_QUIET */ /* set up the selected adapter */ pa->lpAdapter = PacketOpenAdapter(AdapterList[adapter_num]); if (!pa->lpAdapter || (pa->lpAdapter->hFile == INVALID_HANDLE_VALUE)) { free(pa); return NULL; } /* alloc the OID packet */ ppacket_oid_data = (PPACKET_OID_DATA)malloc(sizeof(PACKET_OID_DATA) + PACKET_OID_DATA_SIZE); if (!ppacket_oid_data) { PacketCloseAdapter(pa->lpAdapter); free(pa); return NULL; } /* get the description of the selected adapter */ ppacket_oid_data->Oid = OID_GEN_VENDOR_DESCRIPTION; ppacket_oid_data->Length = PACKET_OID_DATA_SIZE; if (PacketRequest(pa->lpAdapter, FALSE, ppacket_oid_data)) { printf("Using adapter: \"%s\"", ppacket_oid_data->Data); } /* get the MAC address of the selected adapter */ ppacket_oid_data->Oid = OID_802_3_PERMANENT_ADDRESS; ppacket_oid_data->Length = ETHARP_HWADDR_LEN; if (!PacketRequest(pa->lpAdapter, FALSE, ppacket_oid_data)) { printf("ERROR getting the adapter's HWADDR, maybe it's not an ethernet adapter?\n"); PacketCloseAdapter(pa->lpAdapter); free(pa); return NULL; } /* copy the MAC address */ memcpy(ðaddr, ppacket_oid_data->Data, ETHARP_HWADDR_LEN); free(ppacket_oid_data); if (mac_addr != NULL) { /* copy the MAC address to the user supplied buffer, also */ memcpy(mac_addr, ðaddr, ETHARP_HWADDR_LEN); } printf(" [MAC: %02X:%02X:%02X:%02X:%02X:%02X]\n", ethaddr[0], ethaddr[1], ethaddr[2], ethaddr[3], ethaddr[4], ethaddr[5]); /* some more adapter settings */ PacketSetBuff(pa->lpAdapter, PACKET_ADAPTER_BUFSIZE); PacketSetReadTimeout(pa->lpAdapter, 1); PacketSetHwFilter(pa->lpAdapter, NDIS_PACKET_TYPE_ALL_LOCAL | NDIS_PACKET_TYPE_PROMISCUOUS); /* set up packet descriptor (the application input buffer) */ if ((pa->lpPacket = PacketAllocatePacket()) == NULL) { printf("ERROR setting up a packet descriptor\n"); PacketCloseAdapter(pa->lpAdapter); free(pa); return NULL; } PacketInitPacket(pa->lpPacket,(char*)pa->buffer, sizeof(pa->buffer)); if(get_link_state(pa, &mediastate)) { *linkstate = (mediastate == NdisMediaStateConnected ? LINKEVENT_UP : LINKEVENT_DOWN); } return pa; }
int main() { //define a pointer to an ADAPTER structure LPADAPTER lpAdapter = 0; //define a pointer to a PACKET structure LPPACKET lpPacket; int i; DWORD dwErrorCode; //ascii strings char AdapterName[8192]; // string that contains a list of the network adapters char *temp,*temp1; int AdapterNum=0,Open; ULONG AdapterLength; char buffer[256000]; // buffer to hold the data coming from the driver struct bpf_stat stat; // // Obtain the name of the adapters installed on this machine // printf("Packet.dll test application. Library version:%s\n", PacketGetVersion()); printf("Adapters installed:\n"); i=0; AdapterLength = sizeof(AdapterName); 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); temp1=temp+1; i++; } temp++; } 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"); } // 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 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); } PacketInitPacket(lpPacket,(char*)buffer,256000); //main capture loop while(!kbhit()) { // capture the packets if(PacketReceivePacket(lpAdapter,lpPacket,TRUE)==FALSE){ printf("Error: PacketReceivePacket failed"); return (-1); } PrintPackets(lpPacket); } //print the capture statistics if(PacketGetStats(lpAdapter,&stat)==FALSE){ printf("Warning: unable to get stats from the kernel!\n"); } else printf("\n\n%d packets received.\n%d Packets lost",stat.bs_recv,stat.bs_drop); PacketFreePacket(lpPacket); // close the adapter and exit PacketCloseAdapter(lpAdapter); return (0); }
pcap_t * pcap_open_live(const char *device, int snaplen, int promisc, int to_ms, char *ebuf) { register pcap_t *p; NetType type; #ifdef REMOTE /* Retrofit; we have to make older applications compatible with the remote capture So, we're calling the pcap_open_remote() from here, that is a very dirty thing. Obviously, we cannot exploit all the new features; for instance, we cannot send authentication, we cannot use a UDP data connection, and so on. */ char host[PCAP_BUF_SIZE + 1]; char port[PCAP_BUF_SIZE + 1]; char name[PCAP_BUF_SIZE + 1]; int srctype; if (pcap_parsesrcstr(device, &srctype, host, port, name, ebuf) ) return NULL; if (srctype == PCAP_SRC_IFREMOTE) { p= pcap_opensource_remote(device, NULL, ebuf); if (p == NULL) return NULL; p->snapshot= snaplen; p->timeout= to_ms; p->rmt_flags= (promisc) ? PCAP_OPENFLAG_PROMISCUOUS : 0; return p; } #endif /* Init WinSock */ wsockinit(); p = (pcap_t *)malloc(sizeof(*p)); if (p == NULL) { snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno)); return (NULL); } memset(p, 0, sizeof(*p)); p->adapter=NULL; p->adapter=PacketOpenAdapter(device); if (p->adapter==NULL) { snprintf(ebuf, PCAP_ERRBUF_SIZE, "Error opening adapter: %s", pcap_win32strerror()); return NULL; } /*get network type*/ if(PacketGetNetType (p->adapter,&type)==FALSE) { snprintf(ebuf, PCAP_ERRBUF_SIZE, "Cannot determine the network type: %s", pcap_win32strerror()); goto bad; } /*Set the linktype*/ switch (type.LinkType) { case NdisMediumWan: p->linktype = DLT_EN10MB; break; case NdisMedium802_3: p->linktype = DLT_EN10MB; break; case NdisMediumFddi: p->linktype = DLT_FDDI; break; case NdisMedium802_5: p->linktype = DLT_IEEE802; break; case NdisMediumArcnetRaw: p->linktype = DLT_ARCNET; break; case NdisMediumArcnet878_2: p->linktype = DLT_ARCNET; break; case NdisMediumAtm: p->linktype = DLT_ATM_RFC1483; break; default: p->linktype = DLT_EN10MB; /*an unknown adapter is assumed to be ethernet*/ break; } /* Set promisquous mode */ if (promisc) PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_PROMISCUOUS); else PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_ALL_LOCAL); /* Set the buffer size */ p->bufsize = PcapBufSize; p->buffer = (u_char *)malloc(PcapBufSize); if (p->buffer == NULL) { snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno)); goto bad; } p->snapshot = snaplen; /* allocate Packet structure used during the capture */ if((p->Packet = PacketAllocatePacket())==NULL){ snprintf(ebuf, PCAP_ERRBUF_SIZE, "failed to allocate the PACKET structure"); goto bad; } PacketInitPacket(p->Packet,(BYTE*)p->buffer,p->bufsize); /* allocate the standard buffer in the driver */ if(PacketSetBuff( p->adapter, SIZE_BUF)==FALSE) { snprintf(ebuf, PCAP_ERRBUF_SIZE,"driver error: not enough memory to allocate the kernel buffer\n"); goto bad; } /* tell the driver to copy the buffer only if it contains at least 16K */ if(PacketSetMinToCopy(p->adapter,16000)==FALSE) { snprintf(ebuf, PCAP_ERRBUF_SIZE,"Error calling PacketSetMinToCopy: %s\n", pcap_win32strerror()); goto bad; } PacketSetReadTimeout(p->adapter, to_ms); return (p); bad: if (p->adapter) PacketCloseAdapter(p->adapter); if (p->buffer != NULL) free(p->buffer); free(p); return (NULL); }